1.组合总和;
思路依旧,if+for,但是需要注意这道题可以重复取当前的元素,所以在进入下一次递归时不需要将index+1,而还是index;
class Solution {
public:vector<vector<int>> result;vector<int> path;int getsum(vector<int>& nums){int sum = 0;for(int num:nums){sum += num;}return sum;}void backtracking(vector<int>& candidates, int target,int index){ if(getsum(path)>target) return;if(getsum(path) == target){result.push_back(path);return;}for(int i=index;i<candidates.size();++i){if(getsum(path) + candidates[i] > target) continue;path.push_back(candidates[i]);backtracking(candidates,target,i);path.pop_back();}}vector<vector<int>> combinationSum(vector<int>& candidates, int target) {backtracking(candidates,target,0);return result;}
};
2.电话号码的字母组合
class Solution {
public:const string letterMap[10] = {"", // 0"", // 1"abc", // 2"def", // 3"ghi", // 4"jkl", // 5"mno", // 6"pqrs", // 7"tuv", // 8"wxyz", // 9};vector<string> result;string path;void backtracking(string digits, int index){ if(index == digits.size()){result.push_back(path);return;}int digit = digits[index] - '0';for(int i=0;i<letterMap[digit].size();++i){path+=letterMap[digit][i];backtracking(digits,index+1);path.pop_back();}}vector<string> letterCombinations(string digits) {if(digits.size() == 0) return result;backtracking(digits,0);return result;}
};