Given a digit string, 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.

Alt text

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

递归,第一个字符和其余字符的结果的组合为最后的结果

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
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> result;
int len = digits.length();
if (len == 0)
return result;

int num = digits[0] - '0';
string val = valueOf(num);

if (len == 1) {
for (int i = 0, j = val.length(); i < j; i++) {
result.push_back(string(1, val[i]));
}
} else {
vector<string> otherResult = letterCombinations(digits.substr(1));
for (int i = 0, j = val.length(); i < j; i++) {
for (int l = 0, m = otherResult.size(); l < m; l++) {
result.push_back(string(1, val[i]) + otherResult[l]);
}
}
}

return result;
}

string valueOf(int num) {
string result;
switch(num) {
case 2: result = "abc"; break;
case 3: result = "def"; break;
case 4: result = "ghi"; break;
case 5: result = "jkl"; break;
case 6: result = "mno"; break;
case 7: result = "pqrs"; break;
case 8: result = "tuv"; break;
case 9: result = "wxyz"; break;
default: result = "";
}

return result;
}
};