Python C++ 回遡bit mask解Leetcode 78, 90 subsets 1, 2
Subset/Powerset question. 2 approaches :bit mask & backtracking
[codes on Leetcode]https://leetcode.com/problems/subsets/solutions/5186389/bit-mask-backtracking-0ms-beats-100/
[bit/ bit mask playlist]https://www.youtube.com/watch?v=Hw1fnQA8Nk8&list=PLYRlUBnWnd5K8FlzJ6tOswqQcsk7R1Duh
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
沒有留言:
張貼留言