leetcode 39. Combination Sum40

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值