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]
]
public class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> rst = new ArrayList<List<Integer>>();
if(nums == null || nums.length == 0) return rst;
List<Integer> res = new ArrayList<Integer>();
backtrace(rst, res, nums);
return rst;
}
public void backtrace(List<List<Integer>> rst, List<Integer> res, int[] nums){
if(res.size() == nums.length){
rst.add(new ArrayList<Integer>(res));
return;
}else{
for(int i = 0; i < nums.length; i++){
if(!res.contains(nums[i])){
res.add(nums[i]);
backtrace(rst, res, nums);
res.remove(res.size()-1);
}
}
}
}
}