17 Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

img

Example:

1
2
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:

Although the above answer is in lexicographical order, your answer could be in any order you want.


给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

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

img

示例:

1
2
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。

想法

首先用数组或者map存下来数字和字母的对应关系,然后循环+DFS逐位组合字符即可,实际上这道题和求全排列没有什么区别……

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
42
43
44
45
46
#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Solution {
public:
char letter[10][5] = {" ", "*", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> letterCombinations(string digits)
{
vector<string> ans;
if (digits.size() <= 0) {
return ans;
}
string s;
dfs(ans, s, digits, 0);
return ans;
}

void dfs(vector<string> &ans, string &s, const string &digits, int pos)
{
if (pos >= digits.size()) {
ans.push_back(s);
return;
}
else {
int loc = digits[pos] - '0';
for (int i = 0; letter[loc][i] != '\0'; i++) {
s.push_back(letter[loc][i]);
dfs(ans, s, digits, pos + 1);
s.pop_back();
}
}
}
};

int main(void)
{
Solution s;
vector<string> ans = s.letterCombinations("");
for (string s : ans) {
cout << s << endl;
}
return 0;
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×