題目如下:
題目
解題思路
這道題目的解題思路是鸟顺,通過(guò) sorted 函數(shù)先對(duì)候選數(shù)字的list進(jìn)行排序,然后再使用遞歸的方法來(lái)獲取各個(gè)解屈溉。
參考代碼, 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
源碼地址:
https://github.com/jediL/LeetCodeByPython
其它題目:[leetcode題目答案講解匯總(Python版 持續(xù)更新)]
(http://www.reibang.com/p/60b5241ca28e)
ps:如果您有好的建議踱蛀,歡迎交流 :-D晕讲,
也歡迎訪問(wèn)我的個(gè)人博客 苔原帶 (www.tundrazone.com)