LeetCode #78 subsets(子集)python

Question

Given a set of distinct integers, nums, return all possible subsets (the power set).(不同的整數(shù),返回所有可能的子集,離散數(shù)學(xué)中叫power set,個數(shù)是2的len(list)的次方)

Note: The solution set must not contain duplicate subsets.(不重復(fù)的子集)

Example:

#2的三次方8個子集
Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

Thought(思路)

  1. Backtracking(the red arrows 紅色箭頭就是backtracking), DFS(廣度優(yōu)先)
  2. 首先,數(shù)組要排序,在第n層,加入一個元素進入n+1層,刪除剛剛加入的元素,加入第n層的第二個元素......


    thought

Code

class Solution:
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        self.res = []
        def dfs(nums,temp,i):
            self.res.append(temp[:])
            for i in range(i,len(nums)):
                temp.append(nums[i])
                dfs(nums,temp,i+1)
                temp.pop()
                
        dfs(nums,[],0)
        return self.res

Complexity

Time complexity: O(N * 2^n)
Space complexity: O(2^n)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容