//is there some solutions using less space?
public ArrayList<ArrayList<Integer>> permute(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(num.length == 0) return result;
ArrayList<Integer> first = new ArrayList<Integer>();
first.add(num[0]);
result.add(first);
for(int i = 1; i < num.length; i++) {
int size = result.size();
ArrayList<ArrayList<Integer>> tmp = new ArrayList<ArrayList<Integer>>();
for(int j = 0; j < size; j++) {
for(int k = 0; k <= i; k++){
ArrayList<Integer> sub = new ArrayList<Integer>();
sub.addAll(result.get(j));
sub.add(k, num[i]);
tmp.add(sub);
}
}
result = tmp;
}
return result;
}
Permutations
最新推荐文章于 2018-08-18 16:53:37 发布