这一题有点小复杂。。。。主要是递归算法的设计比较考验编程能力。。。没有时空间复杂度的要求,使用递归也比较方便理解,题目描述如下,大概就是使得k个1-9的数之和为n;代码贴到下面,好好理解:
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]]
class Solution {
public:
void combination(vector<vector<int>>& result, vector<int> sol, int k, int n) {
if (sol.size() == k && n == 0) { result.push_back(sol); return ; }//迭代时求和刚好为n,res压栈,返回
if (sol.size() < k) {
for (int i = sol.empty() ? 1 : sol.back() + 1; i <= 9; ++i) {//数字不够的时候
//下一个数太大,不用算下去了,再循环也没什么意义,例如(k=3,n=6),[1,3,4]已经大了,再算[1,3,5-6..]也没啥意义
if (n - i < 0) break;
sol.push_back(i);//否则压栈候选
combination(result, sol, k, n - i);
sol.pop_back();//上一步迭代没有结果,就把上面压栈的数字删掉,换一个数字候选
}
}
}
vector<vector<int>> combinationSum3(int k, int n) {
vector<vector<int>> result;
vector<int> sol;
combination(result, sol, k, n);
return result;
}
};