代码随想录算法训练营第二十天
216.组合总和III
题目链接
文章讲解
视频讲解
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracing(int targetSum, int k, int sum, int startIndex) {
if(sum > targetSum) {
return;
}
if(path.size() == k) {
if(targetSum == sum) result.push_back(path);
return;
}
for(int i = startIndex; i <= 9 - (k - path.size()) + 1; i++) {
sum += i;
path.push_back(i);
backtracing(targetSum, k, sum, i + 1);
sum -= i;
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum3(int k, int n) {
backtracing(n, k, 0, 1);
return result;
}
};
17.电话号码的字母组合
题目链接
文章讲解
视频讲解
class Solution {
private:
const string letterMap[10] = {
"", // 0
"", // 1
"abc", // 2
"def", // 3
"ghi", // 4
"jkl", // 5
"mno", // 6
"pqrs", // 7
"tuv", // 8
"wxyz", // 9
};
vector<string> result;
string path;
void backtracing(string digits, int index) {
if(index == digits.size()) {
result.push_back(path);
return;
}
int digit = digits[index] - '0';
string letter = letterMap[digit];
for(int i = 0;i < letter.size(); i++) {
path.push_back(letter[i]);
backtracing(digits, index + 1);
path.pop_back();
}
}
public:
vector<string> letterCombinations(string digits) {
if (digits.size() == 0) {
return result;
}
backtracing(digits, 0);
return result;
}
};