[LeetCode] 90.Subsets II tag: backtracking

时间:2022-03-10 13:17:26

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: [1,2,2]
Output:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
这个题目思路就是类似于DFS的backtracking. 是[LeetCode] 78. Subsets tag: backtracking 的update版本,或者说更加general的,因为允许有重复了。
所以在Subsets的基础/模板上,先sort nums,再加个判断,在for loop循环中,如果当前的跟前一个元素相同就跳过,相当于每次只取一次同样的数(在同一个for loop中)。
 
1. Constraints
1) edge case len(nums) == 0 => [ [ ] ]  但是还是可以
 
2. Ideas
DFS 的backtracking    T: O(2^n)     S; O(n)
 
3. Code 
 
1) using deepcopy, but the idea is obvious, use DFS [] -> [1] -> [1, 2] -> [1, 2, 3] then pop the last one, then keep trying until the end. 
import copy
class Solution:
def subsets(self, nums: 'List [int]') -> 'List [ List [int] ]' :
ans = []
def helper(nums, ans, temp, pos):
ans.append(copy.deepcopy(temp))
for i in range(pos, len(nums)):
if i > pos and nums[i] == nums[i - 1]:
continue
temp.append(nums[i])
helper(nums, ans, temp, i + 1)
temp.pop()
nums.sort()
helper(nums, ans, [], 0)
return ans
2) Use the same idea , but get rid of deepcopy
 
class Solution:
def subsets(self, nums: 'List [int]') -> 'List [ List [int] ]' :
ans = []
def helper(nums, ans, temp, pos):
ans.append(temp)
for i in range(pos, len(nums)):
if i > pos and nums[i] == nums[i - 1]:
continue
helper(nums, ans, temp + [nums[i]], i + 1)
nums.sort() # Optional
helper(nums, ans, [], 0)
return ans