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]
.
思路同Combination, 题目要求没有重复元素,所以建立一个arraylist标志每一个元素,如果已经选用设为1。
同样,需要每次递归前克隆一个list
public class Solution {
public List<List<Integer>> permute(int[] num) {
List<List<Integer>> result=new ArrayList<List<Integer>>();
if(num==null||num.length<=0){
return result;
}
ArrayList<Integer> solution=new ArrayList<Integer>();
ArrayList<Integer> flag=new ArrayList<Integer>();
for(int i=0;i<num.length;i++){
flag.add(0);
}
getPermute(num,result,solution,flag);
return result;
}
public void getPermute(int[] num, List<List<Integer>> result, ArrayList<Integer> solution, ArrayList<Integer> flag){
if(solution.size()==num.length){
result.add(solution);
return;
}
else{
for(int i=0;i<num.length;i++){
if(flag.get(i)==0){
ArrayList<Integer> solutionCopy=(ArrayList)solution.clone();
ArrayList<Integer> flagCopy=(ArrayList)flag.clone();
solutionCopy.add(num[i]);
flagCopy.set(i,1);
getPermute(num,result,solutionCopy,flagCopy);
}
}
}
}
}