给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: [1,2,2]
输出:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
/**
* @param {number[]} nums
* @return {number[][]}
*/
var subsetsWithDup = function(nums) {
let n = nums.length;
nums = nums.sort((a,b) => {return a - b});
let tmpPath = [];
let res = [];
let hash = {}
let backtrack = (tmpPath,start) => {
res.push(tmpPath);
for(let i = start;i < n;i++){
if(hash[i] || (i > 0 && !hash[i-1] && nums[i-1] == nums[i])) continue;
hash[i] = true;
tmpPath.push(nums[i]);
backtrack(tmpPath.slice(),i+1);
hash[i] = false;
tmpPath.pop();
}
}
backtrack(tmpPath,0);
return res;
};
作者:Alexer-660
链接:https://leetcode-cn.com/problems/subsets-ii/solution/90-zi-ji-ii-by-alexer-660/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
var permute = function(nums) {
let n = nums.length;
let res = [];
let tmpPath = [];
let backtrack = (tmpPath) => {
if(tmpPath.length == n){
res.push(tmpPath);
return;
}
for(let i = 0;i < n;i++){
if(!tmpPath.includes(nums[i])){
tmpPath.push(nums[i]);
backtrack(tmpPath.slice());
tmpPath.pop();
}
}
}
backtrack(tmpPath);
return res;
};
作者:Alexer-660
链接:https://leetcode-cn.com/problems/permutations/solution/46-quan-pai-lie-by-alexer-660/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。