Table of Content
题目如下:
解题思路
这道题目的解题思路是,通过 sorted 函数先对候选数字的list进行排序,然后再使用递归的方法来获取各个解。
参考代码, beats 84%
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
class Solution: def Solver(self, res, path, candidates, target, idx): for i in range(idx, len(candidates)): new_target = target - candidates[i] if new_target < 0: return else: if new_target == 0: res.append(path + [candidates[i]]) else: self.Solver(res, path + [candidates[i]], candidates, new_target, i) def combinationSum(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ path = [] res = [] candidates = sorted(candidates) self.Solver(res, path, candidates, target, 0) return res |
如果您有好的建议,欢迎来信与我交流

也欢迎关注微信公众号“苔原带”

