Problem
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
Input: [1,1,2]
Output:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
Solution (Java)
class Solution {
private List<List<Integer>> ans;
public List<List<Integer>> permuteUnique(int[] nums) {
ans = new ArrayList<>();
permute(nums, 0);
return ans;
}
private void permute(int[] nums, int p) {
if (p >= nums.length - 1) {
List<Integer> t = new ArrayList<>(nums.length);
for (int n : nums) {
t.add(n);
}
ans.add(t);
return;
}
permute(nums, p + 1);
boolean[] used = new boolean[30];
for (int i = p + 1; i < nums.length; i++) {
if (nums[i] != nums[p] && !used[10 + nums[i]]) {
used[10 + nums[i]] = true;
swap(nums, p, i);
permute(nums, p + 1);
swap(nums, p, i);
}
}
}
private void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}
Solution (Javascript)
/**
* @param {number[]} nums
* @return {number[][]}
*/
var permuteUnique = function(nums) {
var res = [];
nums.sort((a, b) => (a - b));
dfs(res, [], nums);
return res;
};
var dfs = function (res, arr, nums) {
var len = nums.length;
var tmp1 = null;
var tmp2 = null;
if (!len) return res.push(arr);
for (var i = 0; i < len; i++) {
if (nums[i] === nums[i - 1]) continue;
tmp1 = Array.from(arr);
tmp1.push(nums[i]);
tmp2 = Array.from(nums);
tmp2.splice(i, 1);
dfs(res, tmp1, tmp2);
}
};
Explain:
跟之前一题的差别是可能有重复的数字,那就先排序一下,遇到重复的数字跳过就好。
Complexity:
- Time complexity : O(n!).
- Space complexity :