题目:电话号码的字母组合
因为未知输入字符串的长度,所以不能手动的定义for循环去暴力求解
联想到树的结构,从一个分支一直走到底,再返回上一个最近的分支;与此题类似,以前一个字符串为基点,向后遍历每一个出现的字符,组成新的字符串。
根据传入的index确定当前数字,然后再根据数字在map中得到对应的字符,以每一个字符为起点,进行函数的递归调用,直到index与输入字符串长度相同
1class Solution
2{
3public:
4 void backTrack(const string& digits, int index, std::unordered_map<char, string>& phoneMap, string& combination, std::vector<string>& combinations)
5 {
6 if(index == digits.size())
7 combinations.push_back(combination);
8 else
9 {
10 char num = digits[index];
11 const string& letters = phoneMap[num];
12 for(const char& letter : letters)
13 {
14 combination.push_back(letter);
15 backTrack(digits, index + 1, phoneMap, combination, combinations);
16 combination.pop_back();
17 }
18 }
19 }
20
21 vector<string> letterCombinations(string digits)
22 {
23 if(digits.empty()) return {};
24 std::unordered_map<char, string> phoneMap
25 {
26 {'2', "abc"},
27 {'3', "def"},
28 {'4', "ghi"},
29 {'5', "jkl"},
30 {'6', "mno"},
31 {'7', "pqrs"},
32 {'8', "tuv"},
33 {'9', "wxyz"}
34 };
35 std::vector<string> combinations;
36 string combination;
37 backTrack(digits, 0, phoneMap, combination, combinations);
38 return combinations;
39 }
40};
来源:语雀原笔记