写dfs的时候遇到了一些问题,直接把curAns给加到list里会出问题,需要先赋值一下再添加,赋值可以:
newAns=curAns[:]
然后再添加就不会出现重复的现象,如果不这么做,添加的实际上是引用,共享curAns的内存,然后curAns变了,list里所有的相关元素都会变,新开一个空间就没事了。
这里set里只能存tuple,只有如此才能hash。
class Solution(object):
ansSet=set()
def combinationSum(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)):
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(newAns))
#print self.ansSet
curAns.pop()
return True
for i in range(p,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算法解决组合求和问题时遇到的具体问题及解决方案。特别关注如何避免重复结果,通过深拷贝而非简单引用的方式更新结果列表,确保结果集合中元素的唯一性。此外,还提供了具体的Python实现代码。
1915

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



