【LEETCODE】216-Combination Sum III [Python]

本文解析了LeetCode上组合总和III的问题,通过回溯法寻找所有可能的组合,使得k个数字之和等于n,数字范围限制在1到9之间,且确保每个组合都是唯一的并按升序排列。

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

题目: https://leetcode.com/problems/combination-sum-iii/


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.

Ensure that numbers within the set are sorted in ascending order.


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]]


题意:

找到所有 k 个数字的组合, 由这 k 个数字相加的和为 n

这几个数字只由 1 to 9 ,并且组合是唯一的,保证这个set的数字是升序的


参考:

http://bookshadow.com/weblog/2015/05/24/leetcode-combination-sum-iii/


回溯法:

http://www.cnblogs.com/steven_oyj/archive/2010/05/22/1741376.html

回溯法是一种选优搜索法,按选优条件向前搜索,以达到目标。

但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,

这种走不通就退回再走的技术为回溯法,而满足回溯条件的某个状态的点称为“回溯点”。



Python

class Solution(object):
    def combinationSum3(self, k, n):
        """
        :type k: int
        :type n: int
        :rtype: List[List[int]]
        """
        
        ans=[]
        
        def search(start,cnt,sums,nums):
            
            if cnt>k or sums>n:
                return
            if cnt==k and sums==n:
                ans.append(nums)
                return
            for x in range(start+1,10):
                search(x,cnt+1,sums+x,nums+[x])
        search(0,0,0,[])
        return ans


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值