1 题目
Given a collection of distinct 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],
[3,2,1]
]
2 解法
public class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> cur = new ArrayList<Integer>();
if(nums.length <= 0){
return result;
}
cur.add(nums[0]);
result.add(cur);
for(int i = 1; i < nums.length; i++){
List<List<Integer>> resultTemp = new ArrayList<List<Integer>>();
for(int j = 0; j <= i; j++){
for(List<Integer> lst : result){
List<Integer> curTemp = new ArrayList<Integer>(lst);
curTemp.add(j, nums[i]);
resultTemp.add(curTemp);
}
}
result = resultTemp;
}
return result;
}
}