216.组合总和III
class Solution {
public:
vector<vector<int>> result;
vector<int> temp;
void backtracking(int begin, int k, int n, int sum){
if(temp.size()==k){
if(sum==n){
result.push_back(temp);
}
return;
}
for(int i = begin; i<=9-(k-temp.size())+1; i++){
if(n-sum<i){
return;
}
temp.push_back(i);
sum += i;
backtracking(i+1, k, n, sum);
temp.pop_back();
sum -= i;
// k++;
}
}
vector<vector<int>> combinationSum3(int k, int n) {
if(n>45 || k<=0){
return result;
}
int sum = 0;
backtracking(1, k, n, sum);
return result;
}
};
参考文章:代码随想录-216.组合总和III
17.电话号码的字母组合
class Solution {
private:
const string lettermap[10] = {
"",
"",
"abc",
"def",
"ghi",
"jkl",
"mno",
"pqrs",
"tuv",
"wxyz"
};
public:
vector<string> result;
string temp;
void backtracking(string& digits, int index){
if(temp.size() == digits.size()){
result.push_back(temp);
return;
}
int digit = digits[index]-'0';
string letters = lettermap[digit];
for(int i=0; i<letters.size(); i++){
temp.push_back(letters[i]);
backtracking(digits, index+1);
temp.pop_back();
}
}
vector<string> letterCombinations(string digits) {
if(digits.size()==0){
return result;
}
backtracking(digits, 0);
return result;
}
};
参考文章:代码随想录-17.电话号码的字母组合