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