Day 23
一、回溯
二、代码
216. 组合总和 III - 力扣(LeetCode)
class Solution {
private:vector<int>path;vector<vector<int>>result;void backtracing(int sum,int k,int n,int startindex){//中止条件if(path.size()==k){if(sum==n) result.push_back(path);return;}//单层for(int i=startindex;i<=9;++i){sum+=i;path.push_back(i);backtracing(sum,k,n,i+1);sum-=i;path.pop_back();}}
public:vector<vector<int>> combinationSum3(int k, int n) {backtracing(0,k,n,1);return result;}
};
17. 电话号码的字母组合 - 力扣(LeetCode)
// 版本一
class Solution {
private:const string letterMap[10] = {"", // 0"", // 1"abc", // 2"def", // 3"ghi", // 4"jkl", // 5"mno", // 6"pqrs", // 7"tuv", // 8"wxyz", // 9};
public:vector<string> result;string s;void backtracking(const string& digits, int index) {if (index == digits.size()) {result.push_back(s);return;}int digit = digits[index] - '0'; // 将index指向的数字转为intstring letters = letterMap[digit]; // 取数字对应的字符集for (int i = 0; i < letters.size(); i++) {s.push_back(letters[i]); // 处理backtracking(digits, index + 1); // 递归,注意index+1,一下层要处理下一个数字了s.pop_back(); // 回溯}}vector<string> letterCombinations(string digits) {s.clear();result.clear();if (digits.size() == 0) {return result;}backtracking(digits, 0);return result;}
};