随笔- 509  文章- 0  评论- 151  阅读- 22万 

Letter Combinations of a Phone Number

2013.12.6 19:52

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.

Input:Digit string "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.

Solution:

  Given a certain digit string and the corresponding mapping between digits [0-9] and letters [a-z],  return all the possible letter combinatios that map to this digit string. Since all the combinations must be enumerated, using DFS is efficient in coding. A mapping array between  digits and letters is needed.

  Code segment is quite short and need no more explanation.

  Time complexity is BIG_PI(i in range(0, len(digit_str))){number of mapping for digit_str[i]}, space complexity is O(len(digit_str)).

Accepted code:

复制代码
 1 // 7CE, 2RE, 1WA, 1AC, too bad~
 2 #include <string>
 3 using namespace std;
 4 
 5 class Solution {
 6 public:
 7     vector<string> letterCombinations(string digits) {
 8         // IMPORTANT: Please reset any member data you declared, as
 9         // the same Solution instance will be reused for each test case.
10         result.clear();
11         
12         dfs(digits, 0, "");
13         
14         return result;
15     }
16 private:
17     vector<string> result;
18     string dict[10] = {
19         " ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"
20     };
21     
22     void dfs(string &digits, int idx, string str) {
23         if(idx == digits.length()){
24             result.push_back(str);
25             // 1RE here, didn't return
26             return;
27         }
28         
29         // 7CE here, dict[digits[idx] - '0'], type mismatch
30         for(int i = 0; i < dict[digits[idx] - '0'].length(); ++i){
31             // 1RE here, 1WA here, wrong index
32             dfs(digits, idx + 1, str + dict[digits[idx] - '0'][i]);
33         }
34     }
35 };
复制代码

 

 posted on   zhuli19901106  阅读(320)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示