电话号码的字母组合

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

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

  • 示例 1:

    输入:digits = "23"
    输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
  • 示例 2:

    输入:digits = ""
    输出:[]
  • 示例 3:

    输入:digits = "2"
    输出:["a","b","c"]

提示:

  • 0 <= digits.length <= 4
  • digits[i] 是范围 [‘2’, ‘9’] 的一个数字。

Solution

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
34
35
36
37
38
39
40
41
#include <iostream>
#include <vector>
#include <map>
using namespace std;

class Solution {
public:
vector<string> letterCombinations(string digits) {
static map<int, string> letterC = {{2, "abc"}, {3, "def"}, {4, "ghi"},
{5, "jkl"}, {6, "mno"}, {7, "pqrs"}, {8, "tuv"},
{9, "wxyz"}};
vector<string> result;
if (digits.size() == 0) {
return result;
}
result.resize(1);

for (int i = 0; i < digits.length(); ++i) {
string letters = letterC[digits[i] - '0'];
int len = result.size();
for (int j = 0; j < len; ++j) {
string str = result[0];
for (int k = 0; k < letters.length(); ++k) {
string temp = str + letters[k];
result.push_back(temp);
}
result.erase(result.begin());
}
}
return result;
}
};

int main() {
vector<string> result;
result = Solution().letterCombinations("23"); // ad ae af bd be bf cd ce cf
for (int i = 0; i < result.size(); ++i) {
std::cout << result[i] << " ";
}
std::cout << std::endl;
}