题目来源:https://leetcode.cn/problems/letter-combinations-of-a-phone-number/description/
C++题解: 递归法。
- 确定回溯函数参数:首先需要一个字符串s来收集叶子节点的结果,一个字符串数组result保存起来,定义为全局变量。参数为题目中给的string digits,和一个用来记录第几个元素ind。
- 确定终止条件:path达到输入数字个数即可停止。
- 确定单层遍历逻辑:确定ind指向的数字,并对其对应的字符集进行遍历。对path进行回溯。
class Solution {
public:
vector<string> res;
string path;
void backtracking(string digits, int ind) {
int len = digits.size();
if(path.size() == len) {
res.push_back(path);
return;
}
char j = 'a';
int num = 0;
if(digits[ind] == '2') {j = 'a'; num = 3; }
if(digits[ind] == '3') {j = 'd'; num = 3; }
if(digits[ind] == '4') {j = 'g'; num = 3; }
if(digits[ind] == '5') {j = 'j'; num = 3; }
if(digits[ind] == '6') {j = 'm'; num = 3; }
if(digits[ind] == '7') {j = 'p'; num = 4; }
if(digits[ind] == '8') {j = 't'; num = 3; }
if(digits[ind] == '9') {j = 'w'; num = 4; }
for(int k = 0; k < num; k++) {
path.push_back(j);
j = j+1;
backtracking(digits, ind+1);
path.pop_back();
}
return;
}
vector<string> letterCombinations(string digits) {
int len = digits.size();
if(len == 0) return res;
backtracking(digits, 0);
return res;
}
};