Given a collection of numbers, return all possible permutations.
For example,[1,2,3]
have the following permutations:[1,2,3]
, [1,3,2]
, [2,1,3]
, [2,3,1]
, [3,1,2]
, and [3,2,1]
.
public List<List<Integer>> permute(int[] num) {
List<List<Integer>> result = new ArrayList<>();
perm(result, num, 0);
return result;
}
public void perm(List<List<Integer>> result, int[] num, int pos) {
if(pos == num.length) {
List<Integer> list = new ArrayList<Integer>();
for(int a:num) list.add(a);
result.add(list);
return;
}
for(int i=pos; i<num.length; i++) {
swap(num, i, pos);
perm(result, num, pos+1);
swap(num, i, pos);
}
}
private void swap(int[] num, int i, int j) {
int tmp = num[i];
num[i] = num[j];
num[j] = tmp;
}