https://leetcode.com/problems/combination-sum/description/
简单的回溯应用,就是第二个算法写的时候没考虑重复情况,如果排好序之后按每个值的个数依次遍历也是可以的
Combination Sum1
class Solution(object):
def combinationSum(self, candidates, target):
combination=[]
def fd(sum,min,l):
for i in candidates:
if i>=min:
if sum+i<target:
nl=l[:]
nl.append(i)
fd(sum+i,i,nl)
if sum+i==target:
nl=l[:]
nl.append(i)
combination.append(nl)
break
if sum+i>target:
break
candidates.sort()
nnl=[]
fd(0,candidates[0],nnl)
return combination
Combination Sum2
class Solution(object):
def combinationSum2(self, candidates, target):
combination=[]
nnl=[]
def fd(m,sum,l):
if m==len(candidates):
return
fd(m+1,sum,l)
if sum+candidates[m]==target:
nl=l[:]
nl.append(candidates[m])
nl.sort()
if nl in combination:
return
else:
combination.append(nl)
return
if sum+candidates[m]<target:
nl=l[:]
nl.append(candidates[m])
fd(m+1,sum+candidates[m],nl)
fd(0,0,nnl)
return combination
本文介绍了LeetCode上组合求和问题的两种解决方案:通过回溯算法寻找所有可能的组合,确保组合中的数值加起来等于目标值。第一种方法直接利用递归实现,第二种方法则考虑了候选数组中元素的重复问题。
5万+

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



