216.组合总和III
https://leetcode.cn/problems/combination-sum-iii/
没什么好说的,在普通组合的基础上加一个当前总和,如果当前总和等于n时才收集进结果之中
class Solution {
public:
vector<int> path;
vector<vector<int>> result;
void backTracking(int k, int n, int cur, int curSum) {
if(path.size() == k) {
if (curSum == n) {
result.push_back(path);
}
return;
}
if(curSum >= n) return;
for(int i = cur; i <= min(9, n - 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, 0);
return result;
}
};
当然还有一些处理方法,如果不用curSum的话,可以在每次回溯的时候把n减去当前节点的值,只要n==0时代表达到要求
class Solution {
public:
vector<int> path;
vector<vector<int>> result;
void backTracking(int k, int n, int cur) {
if(path.size() == k) {
if (n == 0) {
result.push_back(path);
}
return;
}
if(n <= 0) return;
for(int i = cur; i <= min(9, n); 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 result;
}
};
17.电话号码的字母组合
https://leetcode.cn/problems/letter-combinations-of-a-phone-number/
class Solution {
public:
unordered_map<char, string> map = {
{'2', "abc"},
{'3', "def"},
{'4', "ghi"},
{'5', "jkl"},
{'6', "mno"},
{'7', "pqrs"},
{'8', "tuv"},
{'9', "wxyz"}
};
vector<string> result;
string path;
void backTracking(string digits, int cur) {
if(digits.empty()) return;
if(cur == digits.length()) {
result.push_back(path);
return;
}
for(auto iter : map[digits[cur]]) {
path.push_back(iter);
backTracking(digits, cur + 1);
path.pop_back();
}
}
vector<string> letterCombinations(string digits) {
backTracking(digits, 0);
return result;
}
};