[leetcode] 216. Combination Sum III @ python

本文探讨了如何找出所有可能的k个数的组合,这些数的和等于n,且只使用1到9的数字,确保每种组合的唯一性和不重复性。介绍了两种解法:一是使用itertools.combinations()方法进行直接组合筛选;二是采用深度优先搜索(DFS)+回溯算法,通过遍历和递归寻找符合条件的组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Note:

All numbers will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:

Input: k = 3, n = 7
Output: [[1,2,4]]
Example 2:

Input: k = 3, n = 9
Output: [[1,2,6], [1,3,5], [2,3,4]]

解法1

使用itertools.combinations()方法, 直接求排列组合的结果, 然后从结果中找出元组的和为n的元组, 将元组转化为列表.
Time: O(n)
Space: O(1)

代码

class Solution:
    def combinationSum3(self, k, n):
        """
        :type k: int
        :type n: int
        :rtype: List[List[int]]
        """
        nums = range(1, 10)
        com = itertools.combinations(nums, k)
        res = [list(tup) for tup in com if sum(tup) == n]
        return res

解法2

DFS + backtracking. 在DFS函数里, 回溯的条件是当k<0或者n<0, 此时直接返回. 当k=0 并且n=0时, 表明我们找到了k个数字的组合,使得它们的和为n, 将path加到res里. 然后对nums进行遍历和递归.

代码

class Solution:
    def combinationSum3(self, k, n):
        """
        :type k: int
        :type n: int
        :rtype: List[List[int]]
        """
        res = []
        nums = range(1, 10)
        self.dfs(nums, k, n, 0, [], res)
        return res
        
    def dfs(self, nums, k, n, index, path, res):
        # edge case
        if k < 0 or n < 0:
            return
        # when reaching the end
        if k == 0 and n == 0:
            res.append(path)
        for i in range(index, len(nums)):
            self.dfs(nums, k-1, n-nums[i], i+1, path+[nums[i]], res)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值