(力扣记录)39. 组合总和

数据结构/算法:回溯

时间复杂度:O(2^(target))

代码实现:

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        res = []
        stack = []

        def backtrack(i):
            add = sum(stack)
            if add == target:
                res.append(stack[:])
                return
            if add > target or i == len(candidates):
                return
            stack.append(candidates[i])
            backtrack(i)
            stack.pop()
            backtrack(i + 1)
        
        backtrack(0)
        return res

你可能感兴趣的:(力扣算法题目记录,leetcode,算法,python)