题目描述:
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个数之和等于n的组合,只允许使用数字1-9,并且每一种组合中的数字应该是唯一的。
确保组合中的数字以递增顺序排列。
测试样例见题目描述。
解题思路:
回溯法
Python代码:
class Solution:
# @param {integer} k
# @param {integer} n
# @return {integer[][]}
def combinationSum3(self, k, n):
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
本文链接:http://bookshadow.com/weblog/2015/05/24/leetcode-combination-sum-iii/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。