Dya25
216.组合总和III
题目链接: 216.组合总和III
不用额外在构造一个sum
变量用来计算当前的和,直接用n
,通过在n
上操作,用n
减去,最后判断n == 0
。
class Solution {
public:
vector<int> path;
vector<vector<int>> res;
void backtracking(int k, int n, int startIndex) {
if (path.size() == k && 0 == n) {
res.push_back(path);
return;
}
for (int i = startIndex; i <= 9 - (k - path.size()) + 1 && n >= 0/*剪枝*/; ++i) {
path.push_back(i);
backtracking(k, n - i/*回溯*/, i + 1);
path.pop_back();//回溯
}
}
vector<vector<int>> combinationSum3(int k, int n) {
backtracking(k, n, 1);
return res;
}
};
17.电话号码的字母组合
题目链接:17.电话号码的字母组合
深度是digits.size()
,宽度是telephoto[tmp]
。
终止条件用path.size() == digits.size()
也行。
class Solution {
public:
vector<string> telephoto{"", "", "abc" ,"def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> res;
void backtracking(const string& digits, int index, const string& path) {
if (path.size()/*index,也可以*/ == digits.size()/*深度*/) {
res.push_back(path);
return;
}
int tmp = digits[index] - '0';//取出digits中对应的数字
for (auto& i : telephoto[tmp]/*宽度*/) {
backtracking(digits, index + 1/*终止条件和去重*/, path + i/*回溯*/);
}
}
vector<string> letterCombinations(string digits) {
if (digits.empty()) return res;
backtracking(digits, 0, "");
return res;
}
};