描述
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]]
求所有由 1-9 这些数字构成的集合,使得集合里的元素个数为
k
,元素的和为
分析
这道题跟 Combination Sum 以及 Combination Sum II 的思路是一样的,对于这种求所有组合的题目优先想到用递归的方法解决。
因为知道元素可能的取值只有
1
到
代码
class Solution {
public:
vector<vector<int>> combinationSum3(int k, int n) {
vector<vector<int>> res; vector<int> out;
combine(k, n, 1, out, res);
return res;
}
void combine(int k, int n, int num, vector<int>& out, vector<vector<int>>& res) {
if (k == 0 && n == 0) {res.push_back(out); return;}
if (num > 9 || n < 0 || k < 0) return;
combine (k, n, num + 1, out, res);
out.push_back(num);
combine (k - 1, n - num, num + 1, out, res);
out.pop_back();
}
};