leetcode刷题python之组合总和

回溯牛皮啊

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        candidates.sort()
        length = len(candidates)
        result=[]
        
        def backtrack(i,tmp_sum,tmp_list):
            if tmp_sum >target or i == length:
                return
            if tmp_sum == target:
                result.append(tmp_list)
                return
            for j in range(i,length):
                if tmp_sum + candidates[j] > target:
                    break   
                backtrack(j,tmp_sum + candidates[j],tmp_list + [candidates[j]])
            
        backtrack(0,0,[])
        return result

你可能感兴趣的:(leetcode_python)