题目:
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.
思路:
直观思路,递归尝试所有可能组合。
代码实现:
class Solution {
public:
void f(vector<bool> &isSelected, int begin, int remain, int sum, vector<vector<int>> &ans, vector<int> &tmp){
if (sum < 0){
return ;
}
if (remain == 0 && sum == 0){
ans.push_back(tmp);
return ;
}
for (int i = begin; i < isSelected.size(); ++i){
if (isSelected[i] == false){
isSelected[i] = true;
tmp.push_back(i);
f(isSelected, i, remain-1, sum-i, ans, tmp);
tmp.pop_back();
isSelected[i] = false;
}
}
}
vector<vector<int>> combinationSum3(int k, int n) {
vector<bool> isSelected(10, false);
vector<vector<int>> ans;
vector<int> tmp;
f(isSelected, 1, k, n, ans, tmp);
return ans;
}
};