2019.08.09
39.组合总数
- 基本思想:回溯
- 实现:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:candidates.sort()n = len(candidates)res = []def helper(i, tmp_sum, tmp):if tmp_sum > target or i == n:return if tmp_sum == target:res.append(tmp)return helper(i, tmp_sum + candidates[i],tmp + [candidates[i]])helper(i+1, tmp_sum ,tmp)helper(0, 0, [])return resdef combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:candidates.sort()n = len(candidates)res = []def backtrack(i, tmp_sum, tmp):if tmp_sum > target or i == n:return if tmp_sum == target:res.append(tmp)return for j in range(i, n):if tmp_sum + candidates[j] > target:breakbacktrack(j,tmp_sum + candidates[j],tmp+[candidates[j]])backtrack(0, 0, [])return res