给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。
示例 1:
输入:nums = [1,2,2]
输出:[[],[1],[1,2],[1,2,2],[2],[2,2]]
示例 2:
输入:nums = [0]
输出:[[],[0]]
提示:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subsets-ii
参考:
python
# 0090.子集II
class Solution:
def subsetsWithDup(self, nums: [int]) -> [[int]]:
res = []
path = []
def track(nums, startIndex):
res.append(path[:])
for i in range(startIndex, len(nums)):
# 同层去重
if i > startIndex and nums[i] == nums[i-1]:
continue
path.append(nums[i])
track(nums, i+1)
path.pop()
nums = sorted(nums) # 去重需要排序
track(nums,0)
return res
golang
package backTrack
import "sort"
var res [][]int
func subsetsWithDup(nums []int) [][]int {
res = make([][]int, 0)
sort.Ints(nums)
track([]int{}, nums,0)
return res
}
func track(temp,nums []int, start int) {
tmp := make([]int, len(temp))
copy(tmp, temp)
res = append(res, tmp)
for i:=start;i<len(nums);i++ {
if i>start && nums[i] == nums[i-1] {
continue
}
temp = append(temp, nums[i])
track(temp, nums, i+1)
temp = temp[:len(temp)-1]
}
}