回溯法入门,求一个集合的全排列,比如{2,3,5}的全排列为:[[2, 3, 5], [2, 5, 3], [3, 2, 5], [3, 5, 2], [5, 3, 2], [5, 2, 3]]
代码如下:
public class AllPermutations {
public void allPermutations(List<List<Integer>> lists, Integer[] a, int cur) {
if (cur == a.length) {
lists.add(new ArrayList<>(Arrays.asList(a)));
} else {
for (int i = cur; i < a.length; i++) {
swap(a, cur, i);
allPermutations(lists, a, cur+1);
swap(a, cur, i);
}
}
}
public void swap(Integer[] a, int i, int j) {
if (i == j) {
return;
}
a[i] ^= a[j];
a[j] ^= a[i];
a[i] ^= a[j];
}
public static void main(String[] args) {
AllPermutations ap = new AllPermutations();
Integer[] a = {2, 3, 5};
List<List<Integer>> lists = new ArrayList<>();
ap.allPermutations(lists, a, 0);
System.out.println(lists);
System.out.println(lists.size());
}