herrDeng網內搜尋

自訂搜尋

Ads

2024年5月21日 星期二

Python C++ 回遡bit mask解Leetcode 78, 90 subsets 1, 2


Python C++ 回遡bit mask解Leetcode 78, 90 subsets 1, 2
Subset/Powerset question. 2 approaches :bit mask & backtracking
Python 請進
class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        n=len(nums)
        powerSet=[]
        def dfs(idx, subset):
            # Add the current subset to the powerSet
            powerSet.append(subset.copy()) 
            
            for i in range(idx, n):
                subset.append(nums[i])
                dfs(i+1, subset)
                subset.pop() #backtracking
        dfs(0, [])
        return powerSet
        

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章