77. 组合
思路
- 最基础的递归思路
- 剪枝的处理
代码随想录
class Solution {
private:
vector<int> path;
vector<vector<int>> result;
void backtracking(int n, int k, int startIndex) {
if (path.size() == k) {
result.push_back(path);
return;
}
for (int i = startIndex; i <= n - (k - path.size()) + 1; i++) {
path.push_back(i);
backtracking(n, k, i + 1); // 递归
path.pop_back(); // 回溯
}
}
public:
vector<vector<int>> combine(int n, int k) {
backtracking(n, k, 1);
return result;
}
};
216.组合总和III
思路
- 和 77. 组合类似,只不过在输出时加了一层判断。
- 两个剪枝的位置:剪枝1——总和超出限制、剪枝2——剩余数字不够。
代码随想录
class Solution {
private:
vector<int> path;
vector<vector<int>> result;
int sum = 0;
void backtracking(int n, int k, int startIndex) {
if (sum > n) return; // 剪枝1
if (path.size() == k && sum == n) {
result.push_back(path);
return;
}
for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i ++) { // 剪枝2
path.push_back(i);
sum += i;
// 递归
backtracking(n, k, i + 1);
path.pop_back(); // 回溯
sum -= i; // 回溯
}
}
public:
vector<vector<int>> combinationSum3(int k, int n) {
backtracking(n, k, 1);
return result;
}
};
17.电话号码的字母组合
思路
- 数字和字母之间的映射关系;
digits
数字的数目表示深度,每个数字在按键上对应的字母数目表示数目。
代码随想录
class Solution {
private:
// 数字和字母之间的映射关系
string letterMap[10] = {
"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz",
};
vector<string> result;
string s;
void backtracking(string& digits, int index) {
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++) {
s.push_back(letters[i]);
backtracking(digits, index + 1);
s.pop_back();
}
}
public:
vector<string> letterCombinations(string digits) {
if (digits.size() == 0) return result;
backtracking(digits, 0);
return result;
}
};
数字和字母的映射关系也可以通过map
实现:
map<int, string> letterMap = {{1, ""},{2, "abc"},{3, "def"},{4, "ghi"},{5, "jkl"},{6, "mno"},{7, "pqrs"},{8, "tuv"},{9, "wxyz"}};