Problem
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
1 |
|
Explanation
-
Similar to 46. Permutations, but this time there are duplicated numbers in the input list, and we don’t want the result list have duplicated sublist.
-
First, we can sort the input list. We still need a temp list for storing the sublist, and a visited array to check whether the element have been visited or not. Inside the helper method, the base case is if the temp list has length equals to the input array, then we add the temp list as sublist into the result list, and return.
-
To remove duplicated elements, under the for loop, we can check if
i > 0 && nums[i] == nums[i-1] && visited[i-1] == false
, then we ignore the currentnums[i]
. From the above example, we want the first 1, second 1, and 2; in this case, when we iterate to the second 1, it satisifyi > 0 && nums[i] == nums[i-1]
, and nowvisited[i-1] = visited[0] = true
. We don’t want the second 1, first 1, and 2; in this case, when we iterate to the second 1, it satisifyi > 0 && nums[i] == nums[i-1]
andvisited[i-1] = visited[0] = false
.
Solution
1 |
|