一上来看到每一个数字都是可以重复选取,感觉不能用回溯的方法,因为不能标志某一个数字有没有被选取过。我想用栈的方式,但是找不到一个规则能把所有的情况遍历够。
其实还是可以用回溯的方法解决的,只不过和之前的有点不同。
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
if(not candidates):
return []
n=len(candidates)
res=[]
candidates.sort()
def helper(i,tmp,target):
if(target==0):
res.append(tmp)
return
# 提前剪枝 因为candidates是排序之后的,所以如果剩余的target小于candidates[i]就可以停止搜索了
if(i==n or target<candidates[i]):
return
# 还是添加本位置数值
helper(i,tmp+[candidates[i]],target-candidates[i])
# 向下一个位置走去,也就是跳过当前位置去搜索
helper(i+1,tmp,target)
helper(0,[],target)
return res
配合 https://blog.youkuaiyun.com/qq_23262411/article/details/103621823 食用。
res就是保存完整解的全局变量
tmp是保存临时结果的变量
target判断是否得到了可行解
i target 用来剪枝