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].
Difficulty: 80 + 15 (how to skip repeated cases to save time ). My first thought was very simple. On the basis of permutation, I added a checksum statement when adding qualified permutation to permutations. If it is repeated, do not add it. I did this before subset II.
1 if (permutation.size() == num.length) {2 if (!permutations.contains(permutation)) {3 permutations.add(new ArrayList<Integer>(permutation));4 return;5 }6 }
But this time it won't work, report TLE. I started to think, how to save time? I read other people's ideas online, saying that recursive function calls are skipped during repeated element loops. For example, if permutation has already been calculated for [num [0], num [1], num [2], that is, [, 2, then, if permutation calculates [num [1], num [0], num [2] and [, 2], skip this case. In this way, we can leave this part of recursive time.
How can I know if this permutation has occurred before? (Key Points of this question)
First, we need to sort the element set so that duplicate elements can be adjacent. Next, we need to judge the usage of duplicate elements and the previous elements by a line of code. If the element before the first repeating element is not in the current result, we do not need to perform recursion.
1 public class Solution { 2 public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) { 3 Arrays.sort(num); 4 ArrayList<Integer> permutation = new ArrayList<Integer>(); 5 ArrayList<ArrayList<Integer>> permutations = new ArrayList<ArrayList<Integer>>(); 6 boolean[] visited = new boolean[num.length]; 7 helper(permutation, permutations, num, visited); 8 return permutations; 9 }10 11 public void helper(ArrayList<Integer> permutation, ArrayList<ArrayList<Integer>> permutations, int[] num, boolean[] visited) {12 if (permutation.size() == num.length) {13 permutations.add(new ArrayList<Integer>(permutation));14 return;15 }16 17 for (int k = 0; k < num.length; k++) {18 if (k > 0 && !visited[k-1] && num[k] == num[k-1]) continue; 19 if (!visited[k]) {20 visited[k] = true;21 permutation.add(num[k]);22 helper(permutation, permutations, num, visited);23 permutation.remove(permutation.size() - 1);24 visited[k] = false;25 }26 }27 }28 }
Leetcode: permutations II