Keshawn_lu's Blog

Leetcode 17. 电话号码的字母组合

字数统计: 338阅读时长: 1 min
2020/08/26 Share

题目简介:

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

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

示例:

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

思路:

这题和昨天那题有异曲同工之妙,都要用到回溯。

深度优先搜索,定义一个curpos来表示当前指向的字符串位置,每次将数字对应的字母一个个加入字符串并进行下一个位置的遍历,然后将其弹出回溯

curpos == digits.size()时,即字符串遍历完毕,将其加入结果数组即可。

代码如下:

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
class Solution {
public:

vector<string> res;
string temp;

unordered_map<char, string> table{
{'0', " "}, {'1',"*"}, {'2', "abc"},
{'3',"def"}, {'4',"ghi"}, {'5',"jkl"},
{'6',"mno"}, {'7',"pqrs"},{'8',"tuv"},
{'9',"wxyz"}};

void dfs(string& digits, int curpos){

if(curpos == digits.size()){

res.push_back(temp);
return;
}

char now_str = digits[curpos];
for(int i = 0; i < table[now_str].size(); i++){

temp += table[now_str][i];
dfs(digits, curpos + 1);

temp.pop_back(); //弹出元素, 回溯
}

}

vector<string> letterCombinations(string digits) {

if(digits.size() == 0)
return {};

dfs(digits, 0);

return res;
}
};
CATALOG
  1. 1. 题目简介:
  2. 2. 思路:
  3. 3. 代码如下: