Skip to content

Latest commit

 

History

History
67 lines (47 loc) · 1.23 KB

078.Subsets .md

File metadata and controls

67 lines (47 loc) · 1.23 KB

###78.Subsets

题目: https://leetcode.com/problems/subsets/

难度 : Medium

Python代码

class Solution(object):
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        results = [[]]
        for num in nums:
            results.extend([result + [num] for result in results])
        return results
            

可是我不能理解,为嘛我写的这个不work.

⬇️

我的不work因为不能同时改变list和iterate list

def subsets(nums):
    """
    :type nums: List[int]
    :rtype: List[List[int]]
    """
    results = [[]]
    for num in nums:
        for result in results:
            results.extend([result + [num]])
    return results
    

BackTrack 标准解法版

class Solution:
    
    def search(self, nums, S, index):
        if index == len(nums):
            self.results.append(S)
            return
        
        self.search(nums, S + [nums[index]], index + 1)
        self.search(nums, S, index + 1)
        
    def subsets(self, nums):
        self.results = []
        self.search(nums, [], 0)
        return self.results

对每个元素,有两种可能,加入S和不加入S,写起来思路还是很清爽的