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

runtime:0ms

class Solution {
public:
vector<vector<int>> combinationSum3(int k, int n) {
vector<int> path;
vector<vector<int>> result;
helper(k,n,0,1,path,result);
return result;
}

void helper(int k,int target,int base,int pos,vector<int> & path,vector<vector<int>> &result)
{
if(k==0&&base==target)
{
result.push_back(path);
return ;
}
if(k<0||base>target)
return ;
for(int i=pos;i<=9;i++)
{
path.push_back(i);
helper(k-1,target,base+i,i+1,path,result);
path.pop_back();
}
}
};

LeetCode 216. Combination Sum III（数字之和）

2016-05-06 04:17:52

Leetcode22.+Leetcode216. 回溯法之应用（二）：圆括号+组合问题

2017-11-10 15:29:13

【LeetCode】216. Combination Sum III 解题报告

2018-02-21 18:28:39

leetcode 216

2017-11-02 21:14:33

leetcode 216. Combination Sum III DFS + 按照index递归遍历

2017-09-22 10:01:31

leetcode 216. Combination Sum III(深搜框架)

2018-06-27 00:24:11

[leetcode] 216. Combination Sum III 解题报告

2015-12-30 06:57:22

LeetCode 216. Combination Sum III 解题报告

2016-10-24 13:44:37

LeetCode216. Combination Sum III

2016-02-04 20:06:50

[LeetCode 216] Combination Sum III

2015-09-16 15:35:39