Permutations II

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         Arrays.sort(num);
 5         DFS(num,0,new boolean[num.length],new ArrayList<Integer>(),res);
 6         return res;
 7     }
 8     public void DFS(int num[],int start,boolean [] visited,ArrayList<Integer>output,ArrayList<ArrayList<Integer>> res){
 9         if(num.length==start){
10             ArrayList<Integer>temp = new ArrayList<Integer>(output);
11             res.add(temp);
12             return;
13         }
14         for(int i=0;i<num.length;i++){
15             if(!visited[i]){
16                 visited[i]=true;
17                 output.add(num[i]);
18                 DFS(num,start+1,visited,output,res);
19                 output.remove(output.size()-1);
20                 visited[i] = false;
21                 while(i<num.length-1 && num[i]==num[i+1]){
22                     i++;
23                 }
24                 
25             }
26         }
27     }
28 }
View Code

 

 

 

 Arrays.sort();

continue; not break;

posted @ 2014-02-08 04:30  krunning  阅读(125)  评论(0编辑  收藏  举报