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]
.
The idea to distinguish this question with Q46 is that we never insert a duplicate element before previous appeared duplicated element. Say nums[i], nums[i+1] are equal, we first insert nums[i], when inserting nums[i+1], we only insert it to places that are after nums[i]. To do so, we have to keep tracking the position of each insertion. The trick I use here is to save this information to the last element of each vector.
Round 2 Solution:
In round 2, I have been forming my own code pattern when solving such kind of problems. To solve skip duplicate elements, I will first finish recursion part followed by a loop which will check duplicate elements and move index to skip duplicate elements.
No comments:
Post a Comment