Find all the combinations of k numbers that add up to n. Only positive integers from 1 to 9 are allowed in the combination, and there are no repeated numbers in each combination.
Description:
All numbers are positive integers.
The solution set cannot contain repeated 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]]
analysis:
Backtracking, focusing on the wording in backtracking, the for(int i = startIndex; i <= 9; i++) loop simulates the process of downward recursion and upward backtracking of a tree, with the recursive call as the dividing line, the above code is From top to bottom, the following code is from bottom to top, the code is as follows:
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(int k, int n, int sum, int startIndex){
if(sum > n) return; // 剪枝
if(path.size() == k){
if(sum == n){
result.push_back(path);
return;
}
}
for(int i = startIndex; i <= 9; i++){
sum += i; // 处理累加
path.push_back(i); // 处理
backtracking(k, n, sum, i + 1); // 递归
// 一旦完成了递归的调用就准备向上回溯
sum -= i; // 回溯
path.pop_back(); // 回溯
}
}
public:
vector<vector<int>> combinationSum3(int k, int n) {
backtracking(k, n, 0, 1);
return result;
}
};