题目如下:
题目
解题思路
这道题目的解题思路是,通过 sorted 函数先对候选数字的list进行排序,然后再使用递归的方法来获取各个解。
参考代码, beats 84%
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
其它题目:[leetcode题目答案讲解汇总(Python版 持续更新)]
(https://www.jianshu.com/p/60b5241ca28e)
ps:如果您有好的建议,欢迎交流 :-D,
也欢迎访问我的个人博客 苔原带 (www.tundrazone.com)