代码随想录算法训练营第37期 第二十五天 | LeetCode216.组合总和III、17.电话号码的字母组合
一、216.组合总和III
解题代码C++:
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracing(int k, int n, int startIndex)
{
if(n < 0) return;
if(n == 0 && path.size() == k)
{
result.push_back(path);
return;
}
for(int i = startIndex; i <= 9; i ++)
{
path.push_back(i);
backtracing(k, n - i, i + 1);
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum3(int k, int n) {
result.clear();
path.clear();
backtracing(k, n, 1);
return result;
}
};
题目链接/文章讲解/视频讲解:
https://programmercarl.com/0216.%E7%BB%84%E5%90%88%E6%80%BB%E5%92%8CIII.html
二、17.电话号码的字母组合
解题代码C++:
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
};
public:
vector<string> result;
void getCombinations(const string& digits, int index, const string& s)
{
if(index == digits.size())
{
result.push_back(s);
return;
}
int digit = digits[index] - '0';
string letters = letterMap[digit];
for(int i = 0; i < letters.size(); i ++)
getCombinations(digits, index + 1, s + letters[i]);
}
vector<string> letterCombinations(string digits) {
result.clear();
if(digits.size() == 0)
return result;
getCombinations(digits, 0, "");
return result;
}
};
题目链接/文章讲解/视频讲解:
https://programmercarl.com/0017.%E7%94%B5%E8%AF%9D%E5%8F%B7%E7%A0%81%E7%9A%84%E5%AD%97%E6%AF%8D%E7%BB%84%E5%90%88.html