跟上一道题比就改了一个地方,dfs的for循环从下一个开始,上一道是从自己开始dfs
class Solution(object):
ansSet=set()
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
if len(candidates)==0:return []
candidates.sort()
self.ansSet.clear()
for i in range(len(candidates)):
#print "fuck"
self.dfs(candidates, i, target, candidates[i], [])
return list(self.ansSet)
def dfs(self, candi, p, target, curV, curAns):
curAns.append(candi[p])
if curV==target:
#newAns=curAns[:]
self.ansSet.add(tuple(curAns))
#print self.ansSet
curAns.pop()
return True
for i in range(p+1,len(candi)):
if curV+candi[i]<=target:
self.dfs(candi, i, target, curV+candi[i], curAns)
else:
curAns.pop()
return False
curAns.pop()
return False
本文介绍了一种通过调整深度优先搜索(DFS)算法中的循环起始位置来优化组合求和问题的方法。具体实现中,对候选数列进行排序并利用set去重,确保结果集合中不包含重复项。
213

被折叠的 条评论
为什么被折叠?



