17. 电话号码的字母组合(dfs)

 

难度中等

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。

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

 

示例 1:

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

示例 2:

输入:digits = ""
输出:[]

示例 3:

输入:digits = "2"
输出:["a","b","c"]

 

提示:

  • 0 <= digits.length <= 4
  • digits[i] 是范围 ['2', '9'] 的一个数字。

 

 

 

 1 class Solution {
 2 public:
 3     vector<string> res;
 4     unordered_map<char, string> dd_map{
 5             {'2', "abc"},
 6             {'3', "def"},
 7             {'4', "ghi"},
 8             {'5', "jkl"},
 9             {'6', "mno"},
10             {'7', "pqrs"},
11             {'8', "tuv"},
12             {'9', "wxyz"}
13         };
14     void dfs(string& path,string& digits,int level) {
15         if (path.size() == digits.size()) {
16             res.emplace_back(path);
17             return;
18         }
19         for(int i = level; i <= digits.size();i++) {
20             for(char ch : dd_map[digits[i]]) {
21                 path+=ch;
22                 dfs(path,digits,i+1);
23                 path.pop_back();
24             }
25 
26         }
27     }
28     vector<string> letterCombinations(string digits) {
29         string path = "";
30         if (digits.size()==0) return res;
31         dfs(path,digits,0);
32         return res;
33     }
34 };

 

posted @ 2022-03-29 22:42  乐乐章  阅读(71)  评论(0编辑  收藏  举报