题目如下:
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 class Solution {
List<List<Integer>> list = new ArrayList<List<Integer>>();
public List<List<Integer>> permute(int[] num) {
if(num.length == 0) return list;
if(num.length == 1){
List<Integer> sublist = new ArrayList<Integer>();
sublist.add(num[0]);
list.add(sublist);
return list;
}
int len = num.length;
int[] out = new int[len];
int[] used = new int[len];
doPermute(num, out, used, len, 0);
return list;
}
public void doPermute(int[] in, int[] out, int[] used, int length, int current_Len){
if(current_Len == length){
List<Integer> sublist = new ArrayList<Integer>();
for(int x : out){
sublist.add(x);
}
list.add(sublist);
return;
}
for(int i = 0; i < length; i++){
if(used[i] == 1){
continue;
}
used[i] = 1;
out[current_Len] = in[i];
doPermute(in, out, used,length, current_Len+1);
used[i] = 0;
}
}
}