LeetCode(力扣)40. 组合总和 IIPython

LeetCode40. 组合总和 II

    • 题目链接
    • 代码

题目链接

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

代码

class Solution:
    def backtrackingz(self, candidates, target, result, total, path, startindex):
        if target == total:
            result.append(path[:])
            return 
        for i in range(startindex, len(candidates)):
            if i > startindex and candidates[i] == candidates[i-1]:
                continue
            if total + candidates[i] > target:
                break
            path.append(candidates[i])
            total += candidates[i]
            self.backtrackingz(candidates, target, result, total, path, i + 1)
            total -= candidates[i]
            path.pop()

    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:  
        result = []
        candidates.sort()
        self.backtrackingz(candidates, target, result, 0, [], 0)
        return result

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