Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For
example,[1,1,2]
have
the following unique permutations:[1,1,2]
, [1,2,1]
,
and [2,1,1]
.
1 public class Solution { 2 public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) { 3 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); 4 boolean [] visited = new boolean[num.length]; 5 Arrays.sort(num); 6 DFS(num,visited,0,res,new ArrayList<Integer>()); 7 return res; 8 } 9 public void DFS(int []num,boolean[] visited,int start,ArrayList<ArrayList<Integer>>res,ArrayList<Integer>output){ 10 if(start ==num.length){ 11 ArrayList<Integer> temp = new ArrayList<Integer>(); 12 temp.addAll(output); 13 res.add(temp); 14 return; 15 } 16 for(int i=0;i<num.length;i++){ 17 if(!visited[i] ){ 18 if(i>0 && num[i-1]==num[i] && !visited[i-1]) 19 continue; 20 visited[i] = true; 21 output.add(num[i]); 22 DFS(num,visited,start+1,res,output); 23 output.remove(output.size()-1); 24 visited[i] = false; 25 } 26 } 27 } 28 29 30 }
原文:http://www.cnblogs.com/krunning/p/3540025.html