216. Combination Sum III**
https://leetcode.com/problems/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.
Note:
- All numbers will be positive integers.
- The solution set must not contain duplicate combinations.
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]]
C++ 实现 1
可以说思路和 39. Combination Sum** 以及 40. Combination Sum II** 一致了, 只是这里候选数据集变成了 [1, ..., 9]
, 以及限制了组合的个数为 k
. 另外方面需要注意组合中的数字不能重复.
class Solution {
private:
void dfs(int target, int start, int k, vector<int> &cur, vector<vector<int>> &res) {
if (target < 0 || cur.size() > k) return;
if (target == 0 && cur.size() == k) {
res.push_back(cur);
return;
}
for (int i = start; i < 10; ++ i) {
cur.push_back(i);
dfs(target - i, i + 1, k, cur, res);
cur.pop_back();
}
}
public:
vector<vector<int>> combinationSum3(int k, int n) {
vector<vector<int>> res;
vector<int> cur;
dfs(n, 1, k, cur, res);
return res;
}
};