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]
.
1 public class Solution { 2 public ArrayList<ArrayList<Integer>> permute(int[] num) { 3 int len = num.length; 4 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); 5 if(len<=0) return res; 6 boolean [] visited = new boolean[len]; 7 get(res,new ArrayList<Integer>(),0,num,visited); 8 return res; 9 } 10 public void get(ArrayList<ArrayList<Integer>> res,ArrayList<Integer>output,int depth,int []num,boolean []visited){ 11 if(depth==num.length){ 12 ArrayList<Integer> temp = new ArrayList<Integer>(); 13 temp.addAll(output); 14 res.add(temp); 15 return; 16 } 17 for(int i=0;i<num.length;i++){ 18 if(!visited[i]){ 19 visited[i]=true; 20 output.add(num[i]); 21 get(res,output,depth+1,num,visited); 22 output.remove(output.size()-1); 23 visited[i] = false; 24 } 25 } 26 } 27 }