1、组合总和问题
组合总和问题
class Solution {
public:
void backtracking(int k, int n, int startIndex, vector<vector<int>>& result, vector<int>& path) {
if (path.size() == k) {
if (n == 0) result.push_back(path);
return ;
}
for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i++) {
path.push_back(i);
backtracking(k, n - i, i + 1, result, path);
path.pop_back();
}
}
vector<vector<int>> combinationSum3(int k, int n) {
vector<vector<int>> result;
vector<int> path;
backtracking(k, n, 1, result, path);
return result;
}
};
2、电话号码的字母组合
电话号码的字母组合
class Solution {
public:
string letterMap[10] = {
"",
"",
"abc",
"def",
"ghi",
"jkl",
"mno",
"pqrs",
"tuv",
"wxyz"
};
vector<string> result;
string s;
void backtracking(string digits, int index) {
if (index == digits.size()) {
result.push_back(s);
return ;
}
int digit = digits[index] - '0';
string letter = letterMap[digit];
for (int i = 0; i < letter.size(); i++) {
s.push_back(letter[i]);
backtracking(digits, index + 1);
s.pop_back();
}
}
vector<string> letterCombinations(string digits) {
if (digits.size() == 0) return result;
backtracking(digits, 0);
return result;
}
};