代码改变世界

[LeetCode] 78. Subsets tag: backtracking

2018-08-08 00:26  Johnson_强生仔仔  阅读(268)  评论(0编辑  收藏  举报

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]
 
这个题目思路就是类似于DFS的backtracking.
 
1. Constraints
1) No duplicate subsets and neither integers in the nums.
2) 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(temp[:])
            for i in range(pos, len(nums)):
                temp.append()
                helper(nums, ans, temp, i + 1)
                temp.pop()
        
        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)):
                helper(nums, ans, temp + [nums[i]], i + 1)
        helper(nums, ans, [], 0)
        return ans