算法 17. 电话号码的字母组合

https://leetcode.cn/problems/letter-combinations-of-a-phone-number/

题目描述

给定一个仅包含数字2-9的字符串,返回所有它能表示的字母组合。答案可以按任意顺序返回。

思路

递归遍历digits, 记录组合字符串, 完成一次遍历就加入到result

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const std::unordered_map<char, std::string> phoneMap = {
{'2', "abc"},
{'3', "def"},
{'4', "ghi"},
{'5', "jkl"},
{'6', "mno"},
{'7', "pqrs"},
{'8', "tuv"},
{'9', "wxyz"},
};
class Solution {
public:
void backtrack(vector<std::string>& result, const string& digits, int index, std::string& combination) {
if (index == digits.length())
result.push_back(combination);
else {
const string& letters = phoneMap.at(digits[index]);
for (const char& letter : letters) {
combination.push_back(letter);
backtrack(result, digits, index + 1, combination);
combination.pop_back();
}
}
}
std::vector<std::string> letterCombinations(std::string digits) {
std::vector<std::string> result;
if (digits.empty())
return result;
std::string com;
backtrack(result, digits, 0, com);
return result;
}
};