题目:给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。candidates 中的数字可以无限制重复被选取。
思路:回溯
具体:path为遍历数组(栈),先对输入数组排序,当path合大于target时剪枝,等于target时导入res并pop,小于target时继续
代码:
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
if len(candidates) <= 0: return []
candidates.sort()
res = []
path = []
def helper(s, start, end):
for i in range(start, end):
if candidates[i] == target-s:
path.append(candidates[i])
import copy
res.append(copy.copy(path))
path.pop()
break
elif candidates[i] > target-s:
break
else:
path.append(candidates[i])
helper(s+candidates[i], i, end)
path.pop()
helper(0, 0, len(candidates))
return res