46. 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].

---

sort array

check duplication

recursive

---

public class Solution {  
    public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {  
        // Start typing your Java solution below  
        // DO NOT write main() function  
        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();  
        ArrayList<Integer> tmp = new ArrayList<Integer>(); 
        Arrays.sort(num);
        int n = num.length;  
        boolean[] visited = new boolean[n];  
          
        helper(res, tmp, num, visited);  
          
        return res;  
    }  
    private void helper(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> tmp, 
            int[] num, boolean[] visited){  
                
        if(tmp.size() == num.length){  // Base case
            res.add(new ArrayList<Integer>(tmp));  
            return;  
        }  
        for(int i=0; i<num.length; i++){  
            if(!visited[i]){  
                tmp.add(num[i]);  
                visited[i] = true;  
                permuteImp(res, tmp, num, visited);  
                visited[i] = false;  
                tmp.remove(tmp.size()-1);
                
                while(i+1<num.length && num[i+1]==num[i])
                    i++;
            }  
        }  
    }  
}  

 

public class Solution {
    
    public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
        if(num == null) return null;
        // sort the array
        Arrays.sort(num);
        
        // helper
        return helper(num, 0, new boolean[num.length]);
    }
    
    private ArrayList<ArrayList<Integer>> helper(int[] num, int l, boolean[] used){
    
        ArrayList<ArrayList<Integer>> rst = new ArrayList<ArrayList<Integer>>();
        
        if(l == num.length){ // base case
            rst.add(new ArrayList<Integer>());
            return rst;
        }
 
        for(int i = 0; i < num.length; i++){
            
            // check dup
            if(used[i] || i>0 && num[i]==num[i-1] && used[i-1])
                continue;
                
            used[i] = true;
            for(ArrayList<Integer> x : helper(num, l+1, used)){
                x.add(0, num[i]);
                rst.add(x);
            }
            used[i] = false;
        }
        return rst;
    }
}

 

 

posted @ 2013-09-07 03:36  LEDYC  阅读(145)  评论(0)    收藏  举报