Tuesday, January 20, 2015

Permutations II (LeetCode Backtracking)

Question: 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].

Idea: Backtracking depth-first search. To avoid duplication, we first sort the array. Then the integers with the same value are placed at adjacent positions. For each recursive call, we only add the integer at the first unused position and is the first of the unused of the adjacent subarray with the same value.

Time: O(n!) Space: O(n)

Code:
 public class Solution {  
   public List<List<Integer>> permuteUnique(int[] num) {  
     List<List<Integer>> result=new ArrayList<List<Integer>>();  
     List<Integer> path=new ArrayList<Integer>();  
     Arrays.sort(num);  
     boolean[] used=new boolean[num.length];  
     dfs(result,path,num,used);  
     return result;  
   }  
   public void dfs(List<List<Integer>> result, List<Integer> path,int[] num,boolean[] used)  
   {  
     if(path.size()==num.length)  
     {  
       result.add(new ArrayList<Integer>(path));  
       return;  
     }  
     for(int i=0;i<num.length;i++)  
     {  
       if((i!=0&&num[i]==num[i-1]&&used[i-1]==false)||used[i]==true)  
         continue;  
       path.add(num[i]);  
       used[i]=true;  
       dfs(result,path,num,used);  
       used[i]=false;  
       path.remove(path.size()-1);  
     }  
   }  
 }  

No comments:

Post a Comment