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].
Problem: it is similar to permutation, but this time there will be repeated elements, as shown in. If only DFS is used, a duplicate arrangement will be generated:
The number in parentheses represents the number 1 in the sequence. The above DFS generates two 112,121 and 211. We can write two 112 values as follows: 1 (1) 1 (2) 2 and 1 (2) 1 (1) 2, the reason for repetition is that we do not actually distinguish the current 1 from the first few 1 in the sequence. Therefore, if we can ensure that the same elements in the sequence only appear in the sequence ascending order, you can avoid repetition. For example, in the above 112, we only allow 1 (1) 1 (2) 2, and step 1 (2) 1 (1) 2.
You only need to add the highlighted Code as follows during the judgment to achieve this:
1 public class Solution { 2 public List<List<Integer>> permuteUnique(int[] num) { 3 List<List<Integer>> answerList = new ArrayList<List<Integer>>(); 4 ArrayList<Integer> currentList = new ArrayList<Integer>(); 5 boolean[] visited = new boolean[num.length]; 6 7 Arrays.sort(num); 8 DS(answerList, visited, num, currentList); 9 return answerList;10 }11 12 public void DS(List<List<Integer>> answerList,boolean[] visited,int[] num,ArrayList<Integer> currentList){13 boolean find = true;14 for(int i = 0;i < num.length;i++){15 if(i-1>=0 && num[i]== num[i-1] && visited[i-1] == false)16 continue;17 if(!visited[i]){18 currentList.add(num[i]);19 visited[i]= true;20 DS(answerList, visited, num, currentList);21 visited[i]= false;22 currentList.remove(currentList.size()-1);23 find = false;24 }25 }26 if(find){27 ArrayList <Integer> temp = new ArrayList<Integer>(currentList);28 answerList.add(temp);29 }30 }31 }