经典回溯题目 + 剪枝 + 避免重复
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
path = [] #当前路径
res = [] #保存结果列表
#回溯函数
def back_track(candidates, target, index):
if target == 0:
res.append(path[:])
return
#剪枝,小于0就不再递归
if target < 0:
return
#遍历整个列表
for i in range(index, len(candidates)):
#加入当前元素
path.append(candidates[i])
#每次index从i开始,避免出现重复解
back_track(candidates, target - candidates[i], i)
#回溯操作,弹出当前值
path.pop()
back_track(candidates, target, 0)
return res