DFS递归算法
同上一题
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
res = []
self.dfs(candidates,target,0,[],res)
return res
def dfs(self, nums, target , index, path , res):
if target<0:
return
elif target ==0 and path not in res:
res.append(path)
for i in range(index,len(nums)):
self.dfs(nums,target-nums[i],i+1,path+[nums[i]],res)
DP算法(动态规划)
集合的概念
class Solution:
def combinationSum2(self, candidates, target):
candidates.sort()
table = [None] + [set() for i in range(target)] #构造一个多重集合列表,索引下的值等于集合中元素的和
for i in candidates:
if i > target:
break
for j in range(target - i, 0, -1): #当前数字为i,定义j从target-i到0作一次反向遍历,将i+j的集合更新为i的集合与j的集合的并集
#i=1,target=8,j=7,6,5,4,3,2,1,更新顺序为,8,7,6,5,4,3,2
#若为正向遍历,更新顺序为2,3,4,5,6,7,8,那么更新3时,j为2在之前已更新过,(1,1)便会作为2的集合添加到3(1,1,1)
#,实际是没有3个1,为了避免同一个元素i在每个位置的集合中只添加一次,应逆序遍历
table[i + j] |= {elt + (i,) for elt in table[j]} #和为i+j的集合等于和为i的集合与和为j的集合的并集
table[i].add((i,))
return map(list, table[target])