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]
.
Answer:
public class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
ArrayList<Integer> subres = new ArrayList<Integer>();
ArrayList<Integer> num = new ArrayList<Integer>();
for(int i=0;i<nums.length;++i){
num.add(nums[i]);
}
permuteRec(num,res,subres);
return res;
}
public void permuteRec(ArrayList<Integer> nums, List<List<Integer>> res, List<Integer> subres){
int len = nums.size();
if(len ==0){
//clone a new copy, then add!!!
ArrayList<Integer> newcopy = new ArrayList<Integer>(subres);
res.add(newcopy);
return;
}
for(int i=0;i<len;++i){
int n=nums.get(i);
subres.add(n);
nums.remove(i);
permuteRec(nums,res,subres);
//backtrack!!!
nums.add(i,n); //note: specific pos:i!!!
subres.remove(subres.size()-1);
}
return;
}
}
No comments:
Post a Comment