Topic:
Given A collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2]The following unique permutations:
[1,1,2], [1,2,1] , and [2,1,1] .
Test instructions: As with I, the only difference between finding all permutations is that there will be duplicate numbers in the array
Ideas: Join visited to determine whether the location is selected, to avoid the selection of itself, but this will still be tle, then need the most critical step, start Dfs before the nums sort, so that when the DFS when nums[i] = = Nums[i-1] and visited[i-1] ==false words continue, imagine, at this time the number and the previous is the same, the previous one has not been visited to prove that the number of the arrangement has been completed that this number is definitely not used.
Code:
Public classSolution { PublicList<list<integer>> Permuteunique (int[] nums) {List<List<Integer>> List =NewArraylist<list<integer>>(); if(Nums = =NULL|| Nums.length = = 0) returnlist; List<Integer> temp =NewArraylist<integer>(); Boolean[] visited =New Boolean[Nums.length]; Arrays.sort (Nums); //Key 1DFS (list, temp, nums, visited, 0); returnlist; } Public voidDFS (list<list<integer>> List, List<integer> temp,int[] Nums,Boolean[] visited,intcount) { if(Count = =nums.length) {if(!list.contains (temp)) List.add (NewArraylist<integer>(temp)); return; } for(inti = 0; i < nums.length; i++) { if(i > 0 && nums[i-1] = = Nums[i] &&!visited[i-1])//Key 2 Continue; if(Visited[i])Continue; Visited[i]=true; Temp.add (Nums[i]); DFS (list, temp, nums, visited, Count+1); Temp.remove (Temp.size ()-1); Visited[i]=false; } }}
[Leetcode-java] Permutations II