描述

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

Note:

The solution set must not contain duplicate subsets.

For example,

If nums = [1,2,3], a solution is:

[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]

class Solution:
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        cur_array=[[],]
        for num in nums:
            self.dfs(cur_array,num)
        # print(cur_array)
        return cur_array

    def dfs(self,cur_array,num_in):
        # new_array1=cur_array.append(num_in)
        # new_array2=cur_array
        # print(num_in)
        new_array=list(map(lambda x:x+[num_in],cur_array))
        # print(list(new_array))
        cur_array.extend(new_array)


if __name__=='__main__':
    st=Solution()
    st.subsets([1,2,3])

解释:就是普通的动态规划吧,找准规律,所有数字过一遍,每个数字都有添加和不被添加两种情况,所有情况的综合


龙仔
12 声望4 粉丝