Skip to content

Latest commit

 

History

History
43 lines (38 loc) · 1.13 KB

78. Subsets.md

File metadata and controls

43 lines (38 loc) · 1.13 KB

78. Subsets (Medium)

[tag] combination algorithm, DFS

  • for loop for different the length of the sub_set.
  • dfs(lenth, start_number, cur_set)
class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        ans = []
        def dfs(subset_len, s, cur_set):
            # print(subset_len, cur_set)
            if len(cur_set) == subset_len:
                ans.append(cur_set.copy())
                return
            # add different numbers to cur_set
            for i in range(s, len(nums)):
                cur_set.append(nums[i])
                dfs(subset_len, i+1, cur_set)
                cur_set.pop()
        for subset_len in range(len(nums)+1):
            dfs(subset_len, 0, [])
        return ans

New solution on 9/14

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        temp = []
        ans = []
        nums.sort()
        
        def dfs(index):
            ans.append(temp.copy())
            for i in range(index, len(nums)):
                temp.append(nums[i])
                dfs(i+1)
                temp.pop()
        dfs(0)
        return ans