# [leetcode][回溯] 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]]
class Solution {
public:
vector<vector<int>> combinationSum3(int k, int n) {
vector<vector<int> > res;
if (k <= 0 || n <= 0) return res;
vector<int> oneCombination;
combinationSum3Core(k, n, 1, 0, oneCombination, res);
return res;
}
private:
void combinationSum3Core(int k, int n, int start, int sum, vector<int> oneCombination, vector<vector<int> > &res){
if (start > 9 || sum >= n || oneCombination.size() == k){
if (oneCombination.size() == k && sum == n) res.push_back(oneCombination);
return;
}
for (int i = start; i <= 9; ++i){
oneCombination.push_back(i);
combinationSum3Core(k, n, i + 1, sum + i, oneCombination, res);
oneCombination.pop_back();
}
}
};

leetcode测试运行时间不到1ms

• 本文已收录于以下专栏：

## Leetcode|Combination Sum III[回溯]

Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

## LeetCode Combination Sum III

Description: Find all possible combinations of k numbers that add up to a number n, given that ...

## [LeetCode - 回溯] 39. Combination Sum

1 问题 Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all u...

## Combination Sum III C#

Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

## leetcode 216. Combination Sum III

class Solution { void do_once(int k,int n, map, int>&candi) { map, int>newcandi; for (map, int...

## leetCode(31):Combination Sum III

Find all possible combinations of k numbers that add up to a number n, given that only numbers fro...

## [LeetCode]39.Combination Sum&40.Combination Sum II&216.Combination Sum III&377.Combination Sum IV

39.Combination Sum 40.Combination Sum II 216.Combination Sum III 377.Combination Sum IV

举报原因： 您举报文章：深度学习：神经网络中的前向传播和反向传播算法推导 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)