LeetCode--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.

Letter-Combinations-of-a-Phone-Number

note:

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

样例:

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

题意:

给定只包含 2 - 9 之间的一个字符串代表一个数字,返回这个数字所有的组合

思路:

就是根据 2 - 9 所对应的字符进行一个标记,然后直接 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
class Solution {
public:
vector<string> letterCombinations(string digits) {
map<string, string> mp;
mp["2"] = "abc";
mp["3"] = "def";
mp["4"] = "ghi";
mp["5"] = "jkl";
mp["6"] = "mno";
mp["7"] = "qprs";
mp["8"] = "tuv";
mp["9"] = "wxyz";
vector<string> res;
if(digits.empty() || digits.size() == 0) return res;
string tmp;
dfs(res, digits, 0, tmp, mp);
return res;
}

void dfs(vector<string> &res, string digits, int cur, string &tmp, map<string, string> mp){
if(cur == digits.size()){
res.push_back(tmp);
return;
}
string index;
index += digits[cur];
for(int i = 0; i < mp[index].size(); ++i){
tmp.push_back(mp[index][i]);
dfs(res, digits, cur + 1, tmp, mp);
tmp.pop_back();
}
}
};

Runtime:8ms Memory:10.3MB