216.组合总和III
题目链接/文章讲解:代码随想录
视频讲解:和组合问题有啥区别?回溯算法如何剪枝?| LeetCode:216.组合总和III_哔哩哔哩_bilibili
class Solution {
private:
vector<int> set;
vector<vector<int>> result;
int startIndex = 1;
int sum = 0;
public:
vector<vector<int>> combinationSum3(int k, int n) {
if(k * (k + 1) / 2 > n) return {};
backtracking(k, n, 1, k);
return result;
}
void backtracking(int k, int n, int startIndex, int count){
if(set.size() == k){
if(sum == n) result.push_back(set);
return;
}
for(int i = startIndex; i <= 10 - count; i++){
set.push_back(i);
sum += i;
backtracking(k, n, i + 1, count - 1);
set.pop_back();
sum -= i;
}
}
};
17.电话号码的字母组合
题目链接/文章讲解:代码随想录
class Solution {
private:
unordered_map<int, string> hash;
string set;
vector<string> result;
public:
vector<string> letterCombinations(string digits) {
if(digits.empty()) return{};
hash[2] = "abc";
hash[3] = "def";
hash[4] = "ghi";
hash[5] = "jkl";
hash[6] = "mno";
hash[7] = "pqrs";
hash[8] = "tuv";
hash[9] = "wxyz";
backtracking(digits, 0);
return result;
}
void backtracking(const string &digits, int startIndex){
if(set.length() == digits.length()){
result.push_back(set);
return;
}
string str = hash.find((int)(digits[startIndex] - '0'))->second;
for(char s : str){
set += s;
backtracking(digits, startIndex + 1);
set.pop_back();
}
}
};