代码随想录二刷Day25
今日任务
216.组合总和III
17.电话号码的字母组合
语言:C++
216. 组合总和III
链接:https://leetcode.cn/problems/combination-sum-iii/
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
int curSum = 0;
void backtracking(int k, int n, int cur){
if(path.size() == k && curSum == n){
res.push_back(path);
return;
}
else if(path.size() < k && curSum >= n) return;
else if(path.size() == k && curSum < n) return;
for(int i = cur; i <= n && i <= 9; i++){
curSum += i;
path.push_back(i);
backtracking(k, n, i + 1);
curSum -= i;
path.pop_back();
}
}
vector<vector<int>> combinationSum3(int k, int n) {
backtracking(k, n, 1);
return res;
}
};
17. 电话号码的字母组合
链接:https://leetcode.cn/problems/letter-combinations-of-a-phone-number/
class Solution {
public:
vector<string> res;
string path = "";
const string map[10] = {
"", //0
"", //1
"abc", //2
"def", //3
"ghi", //4
"jkl", //5
"mno", //6
"pqrs", //7
"tuv", //8
"wxyz", //9
};
void backtracking(string digits, int index){
if(index == digits.length()){
res.push_back(path);
return;
}
int tmp = digits[index] - '0';
for(int i = 0; i < map[tmp].length(); i++){
path += map[tmp][i];
backtracking(digits, index + 1);
path.pop_back();
}
}
vector<string> letterCombinations(string digits) {
if(digits.length() == 0) return res;
backtracking(digits, 0);
return res;
}
};