17. 电话号码的字母组合
题目地址:
题解思路:回溯
时间复杂度:O(3^m * 4^n)
空间复杂度:O(3^m * 4^n)
代码:
cpp
class Solution {
public:
// map digit to word
string digit_to_word[10] = {
"", // 0
"", // 1
"abc", // 2
"def", // 3
"ghi", // 4
"jkl", // 5
"mno", // 6
"pqrs", // 7
"tuv", // 8
"wxyz", // 9
};
vector<string>ret;
string str;
void backtrack(string& digits, int start){
if(start == digits.size()){
ret.push_back(str);
return ;
}
int id = digits[start] - '0';
string temp = digit_to_word[id];
int size = temp.size();
for(int i = 0; i < size; i++){
str += temp[i];
backtrack(digits, start + 1);
str.pop_back();
}
}
vector<string> letterCombinations(string digits) {
// 1. 返回类型和参数
// 2. 终止
// 3. 单层循环
if(digits.empty()) return ret;
backtrack(digits, 0);
return ret;
}
};
39. 组合总和
题目地址 :39. 组合总和 - 力扣(LeetCode)
题解思路:回溯
时间复杂度 :O(n * 2^n),n个数,每个数考虑选or不选(2^n)
空间复杂度:O(target)
代码:
cpp
class Solution {
public:
vector<vector<int>>ret;
vector<int>arr;
void backtrack(vector<int>& candidates, int target, int sum, int start){
if(sum > target){
return ;
}
if(sum == target){
ret.push_back(arr);
return ;
}
int size = candidates.size();
for(int i = start; i < size; i++){
arr.push_back(candidates[i]);
backtrack(candidates, target, sum + candidates[i], i);
arr.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
// 组合问题:回溯 + 剪枝
backtrack(candidates, target, 0, 0);
return ret;
}
};