代码改变世界

[LeetCode] 90.Subsets II tag: backtracking

2019-04-11 10:21  Johnson_强生仔仔  阅读(257)  评论(0编辑  收藏  举报

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中)。
 
Note: for input [4,4,4,1,4], the output is [[],[1],[1,4],[1,4,4],[1,4,4,4],[1,4,4,4,4],[4],[4,4],[4,4,4],[4,4,4,4]]
if we use only visited = set() before the for loop in the helper function without nums.sort(), we will get results like below:
[[],[4],[4,4],[4,4,4],[4,4,4,1],[4,4,4,1,4],[4,4,4,4],[4,4,1],[4,4,1,4],[4,1],[4,1,4],[1],[1,4]]
 
 
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()
        helper(nums, ans, [], 0)
        return ans

 

3) use visited set to get only one from the duplicates 
class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        ans = []
        def helper(nums, ans, temp, pos):
            ans.append(temp)
            visited = set()
            for i in range(pos, len(nums)):
                if nums[i] not in visited:
                    helper(nums, ans, temp + [nums[i]], i + 1)
                    visited.add(nums[i])
        nums.sort()
        helper(nums, ans, [], 0)
        return ans