3

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

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, so the value passed is indeed the same, but I forgot I was using the value of prefix in the for-loop.
@AntonZ ya, hope the updated table looks clear to you for why the error result looks like that.
1

The problem is that when the recursion occur, when the values are popped from the stack, when you do:

prefix = prefix + numbers.charAt(i);

The changes will occur on each level of the call hierarchy. But when you do:

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

You're only performing prefix + numbers.charAt(i) once.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.