ZhongKuo0228 / study

0 stars 0 forks source link

216. Combination Sum III #114

Open fockspaces opened 11 months ago

fockspaces commented 11 months ago

Back tracking technique either time we can choose pick cur_num or not pick cur_num and we take advantage of the same list for fix space complexity

class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        def backtrack(num, cur_sum, comb):
            if cur_sum > n or len(comb) > k:
                return
            if cur_sum == n and len(comb) == k:
                return ans.append(comb[:])
            for i in range(num, 10):
                comb.append(i)
                backtrack(i + 1, cur_sum + i, comb)
                comb.pop()
        ans = []
        backtrack(1, 0, [])
        return ans