LeetCode(力扣)216. 组合总和 IIIPython

LeetCode216. 组合总和 III

    • 题目链接
    • 代码

题目链接

https://leetcode.cn/problems/combination-sum-iii/
LeetCode(力扣)216. 组合总和 IIIPython_第1张图片

代码

class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        result=[]
        self.backtracking(n, k, 0, 1, [], result)
        return result

    def backtracking(self, targetsum, k, currentsum, startindex, path, result):
        if currentsum > targetsum:
            return 
        
        if len(path) == k:
            if currentsum == targetsum:
                result.append(path[:])
            return
        for i in range(startindex, 9 - (k - len(path)) + 2):
            currentsum += i
            path.append(i)
            self.backtracking(targetsum, k, currentsum, i + 1, path, result)
            currentsum -= i
            path.pop()

你可能感兴趣的:(leetcode,算法,职场和发展,python)