第八周第二题
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.
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]]
解题思路
采用回溯法,在求解时主要是求解和等于n的k项组合选择第一项上,之后,加入已经选择好了第一项x,剩下的问题就是给和等于n-x的k-1项组合选择第一项。
由于本题还有其他约束:1.不能重复;
2.组合内元素升序排列;
因此要在大于x的数中给和等于n-x的k-1组合选择第一项,这样直到k-1为0且n-x为0时,就找到了一个可行的组合。
class Solution(object):
def combinationSum3(self,k,n):
result=[]
def func(start,count,sums,nums):
if count>k or sums>n:
return
if count==k and sums==n:
result.append(nums)
return
for x in range(start+1,10):
func(x,count+1,sums+x,nums+[x])
func(0,0,0,[])
return result
本文探讨了如何使用回溯法解决组合总和III问题,即寻找所有可能的k个数字组合,使得这些数字之和等于n,且仅允许使用1到9之间的数字。文章通过递归方式详细阐述了解决方案,并提供了Python实现代码。
353

被折叠的 条评论
为什么被折叠?



