1.题目描述
Given a collection of numbers, nums
, that might contain duplicates, return all possible unique permutations in any order.
Example 1:
Input: nums = [1,1,2]
Output:
[[1,1,2],
[1,2,1],
[2,1,1]]
Example 2:
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Constraints:
1 <= nums.length <= 8
-10 <= nums[i] <= 10
2.题解
这里用到了两个技巧:
(1)有重复数字,所以先排序,重复数字相邻更方便处理;
(2)用-100这个数组中不可能出现的数字来记录数字是否在路径中,用了O(1)的空间做记录;
要解决重复问题,我们只要设定一个规则,保证在填第 i 个数的时候重复数字只会被填入一次即可。而在本题解中,我们选择对原数组排序,保证相同的数字都相邻,然后每次填入的数一定是这个数所在重复数集合中「从左往右