Leetcode 216:组合总和 III(最详细的解法!!!)

找出所有相加之和为 nk 个数的组合**。**组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。

说明:

  • 所有数字都是正整数。
  • 解集不能包含重复的组合。

示例 1:

输入: k = 3, n = 7
输出: [[1,2,4]]

示例 2:

输入: k = 3, n = 9
输出: [[1,2,6], [1,3,5], [2,3,4]]

解题思路

这个问题是之前问题的衍生,而且比之前的问题容易,我们只要在原有的基础上稍加修改即可。

Leetcode 39:组合总和(最详细的解法!!!)

Leetcode 40:组合总和 II(最详细的解法!!!)

class Solution:
    def combinationSum3(self, k, n):
        """
        :type k: int
        :type n: int
        :rtype: List[List[int]]
        """
        result = list()
        self._combinationSum3(n, 1, list(), result, k)
        return result

    def _combinationSum3(self, target, index, path, res, k):
        if target == 0 and len(path) == k:
            res.append(path)
            return 

        if path and target < path[-1]:
            return
       
        for i in range(index, 10):
            self._combinationSum3(target-i, i + 1, path+[i], res, k)

我们仅仅增加了一个len(path) == k

同样的,对于递归可以解决的问题,我们都应该思考是不是可以通过迭代解决。

class Solution:
    def combinationSum3(self, k, n):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        result = list()
        stack = [(1, list(), n)]
        
        while stack:
            i, path, remain = stack.pop()
            while i < 10:
                if path and remain < path[-1]:
                    break
                if i == remain and len(path) == k - 1: # add
                    result.append(path + [i])
                stack += [(i + 1, path + [i],  remain - i)]
                i+=1

        return result 

同样也只是一点小小的修改。

这个问题有一个非常pythonic的解法,使用itertools.combinations

class Solution(object):
    def combinationSum3(self, k, n):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        return [x for x in itertools.combinations(range(1, 10), k) if sum(x) == n]

当然我们这里也可以写出基于combinations的版本,大家可以试试!!!

我将该问题的其他语言版本添加到了我的GitHub Leetcode

如有问题,希望大家指出!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值