题目:
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]]
Difficulty: Medium
翻译&分析:
Combination Sum第三道,给定一个数列,要求找出所有的子集,使每个子集有k个元素,子集元素之和为n,照比前两道稍有难度增加,实际上换汤不换药,具体分析详见:Combination Sum题解
代码:
class Solution {
vector<vector<int>> ret;
vector<int> curr;
public:
void search(int k, int n, int i) {
if (n == 0 && k == 0) {
ret.push_back(curr);
return;
}
if (k < 0 || n < 0 || i > 9) return;
if ((k == 0 && n != 0) || (n == 0 && k != 0)) return;
curr.push_back(i);
search(k - 1, n - i, i + 1);
curr.pop_back();
search(k, n, i + 1);
}
vector<vector<int>> combinationSum3(int k, int n) {
if (k <= 0 || n <= 0 || k >= n) return ret;
search(k, n, 1);
return ret;
}
};