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]]
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Combination Sum III.
class Solution {
public:
vector<vector<int>> combinationSum3(int k, int n) {
vector<vector<int>> ret;
vector<int> path;
int target = ;
helper(k, n, , , target, path, ret);
return ret;
}
void helper(const int k ,const int n, int i_th, int prev, int& target, vector<int>& path, vector<vector<int>>& ret){
if(i_th == k && n == target) {
ret.push_back(path);
return ;
}
for(int i=prev+; i < ; i++){
path.push_back(i);
target += i;
helper(k, n, i_th+, i, target, path, ret);
target -= i;
path.pop_back();
}
}
};