77. Combinations
回溯算法的根本为穷举,所以可以解决组合的问题
他的根本也是树的问题,k 限制了树的高度,n 限制了树的宽度
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
void backtracking(int n, int k, int startIndex){
if(path.size() == k){
res.push_back(path);
return;
}
for(int i=startIndex; i<= n; i++){
path.push_back(i);
backtracking(n, k, i+1);
path.pop_back();
}
}
vector<vector<int>> combine(int n, int k) {
backtracking(n, k, 1);
return res;
}
};
216. Combination Sum III
基本思路与77相同
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
int sum = 0;
void findPath(int k, int n, int startIndex){
if(path.size() == k){
if(sum == n){
res.push_back(path);
}
return;
}
for(int i=startIndex; i<=9; i++){
sum += i;
path.push_back(i);
findPath(k, n, i+1);
sum -= i;
path.pop_back();
}
}
vector<vector<int>> combinationSum3(int k, int n) {
sum = 0;
findPath(k, n, 1);
return res;
}
};
这里有个小问题

这里要用i+1, 不能用i++
优化:
这里要看哪些是不需要的操作
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
int sum = 0;
void findPath(int k, int n, int startIndex){
if(path.size() == k){
if(sum == n){
res.push_back(path);
}
return;
}
for(int i=startIndex; i<=9; i++){
sum += i;
path.push_back(i);
if(sum > n){
sum -= i;
path.pop_back();
return;
}
findPath(k, n, i+1);
sum -= i;
path.pop_back();
}
}
vector<vector<int>> combinationSum3(int k, int n) {
sum = 0;
findPath(k, n, 1);
return res;
}
};
优化部分:

17. Letter Combinations of a Phone Number
思路没什么问题,但是我想的还是用for循环去找每个数字对应的字母,但是这样会runtime error
更好的是把所有的直接写到一个子集里面,直接用数字查找
class Solution {
private:
const string letterMap[8] = {
"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz",
};
public:
vector<string> res;
string path;
void findPath(string digits, int index){
if(path.size() == digits.length()){
res.push_back(path);
return;
}
int num = digits[index] - '0'-2;
string letters = letterMap[num];
for(int i=0; i<letters.length(); i++){
path += letters[i];
findPath(digits, index+1);
path.pop_back();
}
}
vector<string> letterCombinations(string digits) {
if(digits == "") return res;
findPath(digits, 0);
return res;
}
};
tips:
1.string在末尾添加一个值的方法:
1)string += val;
2)string.push_back();
3)string.append(1,'a'); 1表示添加的内容有几位,后面为添加的内容
2.string在末尾删除一个值的方法
1)string.erase(string.end()-1);
*erase(pos, len),删除pos这一位置后面length-1位,这里也可用迭代器表示
str.erase (str.begin()+5, str.end()-9); //删除迭代器范围的字符
2)string.pop_back();
3)可以用resize直接缩短
3.char, int, string 转换
1)int = (int) char 这里虽然转换成ASC码的数字
如 a = '0' , 此时输出48
2) int = char-48或 int = char-'a'
3)to_string
4)stoi
复习:257. Binary Tree Paths
文章介绍了如何使用回溯算法解决组合问题,如77.Combinations和216.CombinationSumIII,强调了i+1的使用以及无效操作的避免。此外,还讨论了17.LetterCombinationsOfAPhoneNumber问题的优化方法,通过预定义数字到字母的映射来提升效率。
1384

被折叠的 条评论
为什么被折叠?



