216. 组合总和 III(Combination Sum III)

216. 组合总和 III(Combination Sum III)

题解

回溯+剪枝

  1. 初试化结果数组 r e s res res

  2. 定义回溯函数 h e l p ( c o u n t , i , t m p , t a r g e t ) help(count,i,tmp,target) help(count,i,tmp,target),其中 c o u n t count count表示当前已经使用的数字数, i i i表示当前访问的数字, t m p tmp tmp表示当前中间结果, t a r g e t target target表示下一步的目标和。

    • c o u n t = = k count==k count==k,说明已经使用了 k k k个数:
      • t a r g e t = = 0 target==0 target==0,表示 t m p tmp tmp的和等于 n n n,将 t m p tmp tmp加入 r e s res res
      • return
    • 遍历区间 [ i , 10 ) [i,10) [i,10)
      • 剪枝,若 j > t a r g e t j>target j>target,说明接下来的数字都比目标和大, b r e a k break break
      • 执行回溯 h e l p ( c o u n t + 1 , j + 1 , t m p + [ j ] , t a r g e t − j ) help(count+1,j+1,tmp+[j],target-j) help(count+1,j+1,tmp+[j],targetj)
  3. 执行 h e l p ( 0 , 1 , [ ] , n ) help(0,1,[],n) help(0,1,[],n)

  4. 返回 r e s res res

复杂度分析

  • 时间复杂度: O ( n ! ) O\left(n!\right) O(n!),进行了一次遍历。
  • 空间复杂度: O ( 1 ) O(1) O(1)

Python

class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        res=[]
        def helper(count,i,tmp,target):
            print(count,i,tmp,target)
            if(count==k):
                if(target==0):
                    res.append(tmp)
                return
            for j in range(i,10):
                if(j>target):
                    break
                helper(count+1,j+1,tmp+[j],target-j)
        helper(0,1,[],n)
        return res

Java(待完成)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值