Day 25 回溯算法
216. 组合总和III
class Solution {
vector<vector<int>> rst;
vector<int> path;
int sum = 0;
void backtracking(int k, int n, int cur)
{
if (path.size() == k && sum == n)
{
rst.push_back(path);
return;
}
for (int i = cur; i < 10; ++i)
{
path.push_back(i);
sum += i;
backtracking(k, n, i + 1);
sum -= i;
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum3(int k, int n) {
rst.clear();
path.clear();
sum = 0;
backtracking(k, n, 1);
return rst;
}
};
17. 电话号码的字母组合
class Solution {
vector<string> rst;
string path;
const unordered_map<char, string> table = {
{'2', "abc"},
{'3', "def"},
{'4', "ghi"},
{'5', "jkl"},
{'6', "mno"},
{'7', "pqrs"},
{'8', "tuv"},
{'9', "wxyz"}
};
void backtracking(const string &digits, int idx)
{
if (path.size() == digits.size())
{
rst.push_back(path);
return;
}
for (int i = 0; i < table.at(digits[idx]).size(); ++i)
{
path.push_back(table.at(digits[idx])[i]);
backtracking(digits, idx + 1);
path.pop_back();
}
}
public:
vector<string> letterCombinations(string digits) {
if (digits.empty()) return {};
rst.clear();
path = "";
backtracking(digits, 0);
return rst;
}
};
文章来源地址https://www.toymoban.com/news/detail-605389.html
文章来源:https://www.toymoban.com/news/detail-605389.html
到了这里,关于算法刷题Day 25 组合总和III+电话号码的字母组合的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!