版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014485485/article/details/80957322
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]]
给定1~9的数,找出k个数的和为n的所有组合数
思路:还是递归+dfs,然后就是判断,当前组合size为k,和为n.
class Solution {
public:
vector<vector<int>> combinationSum3(int k, int n) {
vector<vector<int> > ans;
vector<int> cur;
dfs(k, n, 1, ans, cur);
return ans;
}
void dfs(int k, int n,int start, vector<vector<int> >& ans, vector<int>& cur) {
if (cur.size() > k || n < 0) return;
if (cur.size() == k && n == 0) {
ans.push_back(cur);
return;
}
for (int i = start; i <= 9; i++) {
cur.push_back(i);
dfs(k, n - i, i + 1, ans, cur);
cur.pop_back();
}
}
};