47 Permutations II
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2]
have the following unique permutations:
The Idea: The key is to identify when the next duplicate will take place. I think it is best illustrated through an example. Suppose that our current set of new unique permutations are: [[123,4,3,123], [4,123,3,123], [4,3,123,123]]
, and that the algorithm added the number 123
after index 1 into the array [4,3,123]
. The next iteration would append 123
to the right of index 2 in [4,3,123]
, which would identify as a duplicate.
Complexity: O(n!) time (worse case - no duplicates), and O(1) space
Last updated