0
点赞
收藏
分享

微信扫一扫

LeetCode_String_17. Letter Combinations of a Phone Number 电话号码的字母组合(C++)


目录

​​1,题目描述​​

​​英文描述​​

​​中文描述​​

​​2,思路​​

​​3,AC代码​​

​​4,解题过程​​

1,题目描述

英文描述

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.

 

Example:

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 不对应任何字母。

LeetCode_String_17. Letter Combinations of a Phone Number 电话号码的字母组合(C++)_LeetCode

示例:

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

2,思路

题目意思比较清楚,相当于全排列,这里使用DFS递归的方法,获取全部组和:

  • 使用深度表示当前遍历到的数字字符;
  • 函数中遍历所有数字字符对应的英文字母,并继续向下搜索;
  • 搜索出口是:深度depth等于所给字符串的长度,即所有数字字符遍历完毕,这时将当前拼接成的字符串tem添加到ans中;
  • 记得弹出字符串最右端的元素,以便获得其他字符组和;

LeetCode_String_17. Letter Combinations of a Phone Number 电话号码的字母组合(C++)_string_02

 

3,AC代码

class Solution {
public:
vector<string> ans;
unordered_map<char, vector<char>> data;
void dfs(string digits, int depth, string tem){
if(depth >= digits.length()){
ans.push_back(tem);
return;
}
for(auto cha : data[digits[depth]]){ //利用深度depth定位当前遍历的数字
tem += cha;
dfs(digits, depth+1, tem);
tem.pop_back(); // 注意弹出最外层字符
}
}
vector<string> letterCombinations(string digits) {
if(digits.length() == 0){ //可能出现输入字符串为空的现象
return ans;
}
data['2'] = {'a', 'b', 'c'};
data['3'] = {'d', 'e', 'f'};
data['4'] = {'g', 'h', 'i'};
data['5'] = {'j', 'k', 'l'};
data['6'] = {'m', 'n', 'o'};
data['7'] = {'p', 'q', 'r', 's'};
data['8'] = {'t', 'u', 'v'};
data['9'] = {'w', 'x', 'y', 'z'};
string tem;
dfs(digits, 0, tem);
return ans;
}
};

4,解题过程

由于形式比较直接,这里采用map+DFS的递归处理方法,效果还可以

LeetCode_String_17. Letter Combinations of a Phone Number 电话号码的字母组合(C++)_git_03

举报

相关推荐

0 条评论