78. 子集
https://leetcode-cn.com/problems/subsets/
给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
输入: nums = [1,2,3]
输出: [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
回溯代码
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
n = len(nums)
def helper(i, tmp):
res.append(tmp)
for j in range(i, n):
helper(j + 1,tmp + [nums[j]] )
helper(0, [])
return res
90. 子集 II
https://leetcode-cn.com/problems/subsets-ii/
给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
输入: [1,2,2]
输出: [[], [1], [1, 2], [1, 2, 2], [2], [2, 2]]
回溯代码
class Solution(object):
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
n = len(nums)
nums.sort()
def helper(idx, tmp):
res.append(tmp)
for i in range(idx, n):
if i > idx and nums[i] == nums[i-1]:
continue
helper(i+1, tmp + [nums[i]])
helper(0, [])
return res