码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 90.Subsets II tag: backtracking

时间:2019-04-11 10:41:08      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:copy   inpu   url   deepcopy   htm   style   题目   loop   ble   

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()
        helper(nums, ans, [], 0)
        return ans

 

 

 

[LeetCode] 90.Subsets II tag: backtracking

标签:copy   inpu   url   deepcopy   htm   style   题目   loop   ble   

原文地址:https://www.cnblogs.com/Johnsonxiong/p/10687993.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!