Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive permutation in Java generating wrong result

The problem is to generate lexicographic permutations.

At first, my code was like this:

public class Problem24 {
public static void main(String[] args) {
    permutation("","123");
}

public static void permutation(String prefix, String numbers) {
    if (numbers.length() == 0) {
        System.out.println(prefix);
    } else {
        for (int i = 0; i < numbers.length(); i++) {
            prefix = prefix + numbers.charAt(i);
            permutation(prefix,numbers.substring(0, i)+numbers.substring(i+1));
        }
    }

}
}

The result:

123
1232
1213
12131
12312
123121

When I changed this two lines from

prefix = prefix + numbers.charAt(i);
permutation(prefix,numbers.substring(0, i)+numbers.substring(i+1));

to:

permutation(prefix + numbers.charAt(i),numbers.substring(0, i)+numbers.substring(i+1));

The result becomes right.

This two ways seems equivalent to me. Can someone explain what's different and why the first one would generate wrong result.

Thanks

like image 685
AntonZ Avatar asked Dec 11 '25 18:12

AntonZ


1 Answers

The following one keep adding changes to the prefix between each iteration in for-loop

prefix = prefix + numbers.charAt(i);
permutation(prefix,numbers.substring(0, i)+numbers.substring(i+1));

while this one only pass the changes on prefix to the next level of invocation, it match the purpose of this recursive function well

permutation(prefix + numbers.charAt(i),numbers.substring(0, i)+numbers.substring(i+1));

To visualize the recursive call under each level:

(Correct version)

Level:  1  |   2  |   3
        -- | ---- |  ---
prefix  1  |  12  |  123
           |  13  |  132
        2  |  21  |  213
           |  23  |  231
        3  |  31  |  312
           |  32  |  321

(Wrong version)

Level:   1  |   2    |   3
        --- | ------ | -----
prefix   1  |  12    |  123
            |  123   |  1232
        12  |  121   |  1213
            |  1213  |  12131
       123  |  1231  |  12312
            |  12312 |  123121
like image 105
Paul Lo Avatar answered Dec 13 '25 06:12

Paul Lo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!