Leetcode 216. Combination Sum III

该问题是一个寻找所有可能的、由1到9的数字组成的、且每个数字最多使用一次的k个数之和为n的组合的问题。解决方案是使用深度优先搜索(DFS)策略,从数字1开始递归地尝试所有可能的组合,将符合条件的组合添加到结果列表中。
摘要由CSDN通过智能技术生成

Problem

Find all valid combinations of k numbers that sum up to n such that the following conditions are true:

  • Only numbers 1 through 9 are used.
  • Each number is used at most once.

Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.

Algorithm

Use dfs solve it.

Code

class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        ans = []
        save = [0] * 9
        def dfs(s, n, d):
            nonlocal save, ans, k
            if 0 == n and d == k:
                ans.append(save[0:d])

            for i in range(s, 10):
                save[d] = i
                if n >= i and d < k:
                    dfs(i+1, n-i, d+1)

        dfs(1, n, 0)
        return ans
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值