Permutations II
Given A collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2] has the following unique permutations:
[1,1,2], [1,2,1], and [2,1,1].
Solution 1:
or a classic recursive template. The situation that needs to be handled is: we sort num First, then we can only select sequentially, so we avoid generating duplicate solution.
Example: 1 2 3 4 4 4 5 6 7 8
444 This method can only be selected: 4, 44, 444 consecutive these three kinds of methods
We use an array of visit to record which ones are selected.
1 Public classSolution {2 PublicList<list<integer>> Permuteunique (int[] num) {3list<list<integer>> ret =NewArraylist<list<integer>>();4 if(num = =NULL|| Num.length = = 0) {5 returnret;6 }7 8 //for deal with the duplicate solution, we should sort it.9 arrays.sort (num);Ten Boolean[] Visit =New Boolean[num.length]; One ADFS (NUM,NewArraylist<integer>(), RET, visit); - - returnret; the } - - Public voidDfsint[] num, arraylist<integer> path, list<list<integer>> ret,Boolean[] visit) { - intLen =num.length; + if(path.size () = =Len) { -Ret.add (NewArraylist<integer>(path)); + return; A } at - for(inti = 0; i < Len; i++) { - //Can only be selected consecutively, thus avoiding the generation of duplicate solution. - //Example: 1 2 3 4 4 4 5 6 7 8 - //444 This method can only be selected: 4, 44, 444 consecutive these three kinds of methods - if(Visit[i] | | (I! = 0 && visit[i-1] && num[i] = = Num[i-1])) { in Continue; - } to + //recursion and backtracking -Visit[i] =true; the Path.add (Num[i]); * dfs (num, path, RET, visit); $Path.remove (Path.size ()-1);Panax NotoginsengVisit[i] =false; - } the } +}
View Code
GITHUB:
Https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/permutation/PermuteUnique.java
Leetcode:permutations II Problem Solving report