LeetCode-39-Combination Sum, 回溯dfs,Python的list.append()覆盖前面,tuple,set
2017-09-14 17:02
447 查看
写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
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
相关文章推荐
- python 使用list.append()后前面的数据被后面的数据覆盖-解决办法
- python 使用list.append()后前面的数据被后面的数据覆盖-解决办法
- Python--list,tuple,dict,set.
- Python中list,tuple,dict,set的区别和用法
- [转]python的dict,set,list,tuple应用
- Python学习笔记-四类数据存储结构:list、tuple、dict以及set
- python(list,tuple,dict,set)
- Python中关于str,list,tuple,set,dict的区别和联系
- python基础31[list+tuple+set+dict+str+file的成员方法]
- python 列表list 元组tuple 字典dict 集合set 介绍
- Python List+Tuple+Dict+Set小结
- python再复习(2)list、tuple、条件判断和循环、字典和set
- python的dict,set,list,tuple简单分析
- python之list,tuple,set,dict
- Python List+Tuple+Dict+Set小结
- 回溯之Leetcode39——Combination Sum
- python31初级[list+tuple+set+dict+str+file的成员方法]
- Python3 与 C# 基础语法对比(List、Tuple、Dict、Set专栏)
- Python:数据结构(list, tuple, Dict & Set)
- Python set list dict tuple 区别