题目描述
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]]
思路
DFS,每个位置安排 1~9 的数字,如果当前位置安排了 x ,下一个位置从大于当前位置的数字开始安排。
代码
class Solution {
public:
vector<vector<int>> combinationSum3(int k, int n) {
vector<vector<int>> ans;
vector<int> res;
dfs(k, n, 1, 0, res, ans, 0);
return ans;
}
void dfs(int k, int n, int index, int cur, vector<int>& res, vector<vector<int>>& ans, int cnt) {
if (cur == n && cnt == k) {
vector<int> tmp {res.begin(), res.end()};
ans.push_back(tmp);
return;
}
if (cur > n || cnt > k) return;
for (int i=index; i<=9; ++i) {
res.push_back(i);
dfs(k, n, i+1, cur+i, res, ans, cnt+1);
res.pop_back();
}
return;
}
};