采用回溯算法:
代码:
class Solution:
def fuc(self, candidates: List[int], target: int) -> List[List[int]]:
if target < candidates[0]:
return []
res = []
for i,c in enumerate(candidates):
if c == target:
res.append([c])
return res
next_res = self.fuc(candidates[i:], target - c)
for elm in next_res:
elm.insert(0,c)
res.append(elm)
return res
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
res = self.fuc(candidates, target)
return res