Letter Combinations of a Phone Number:

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.

简单讲讲这道题的思路吧。一开始想到的方法是,由给定的digits字符串的每个字符,确定对应的若干个(3或4)字符,然后通过递归,从底层开始,每次将这一层的字符和vector中的字符串组合一下,再返回给上一层。

思路是挺清晰也挺简单的,不过c++实现过程中也遇到了一点困难。

  • char转换成string的问题。递归最底层要实现这个,“”+ ch并不能做到转string,最后是用一个空的string,push_back字符得到想要的结果。
  • digits的字符对应若干个字符的问题。由于太久没有写这些东西,脑子不是很清晰,一开始也写错了,最终跟这个相关的代码也是有些乱的。

第二种是非递归的方法,每次把数字对应的3或4个字符添加到结果集合中。

最后有给出python实现的代码,非递归,非常简单。

  1. class Solution {
  2. public:
  3. vector<string> letterCombinations(string digits) {
  4. return combine(digits,0);
  5. }
  6. std::vector<string> combine(string digits,int len){
  7. vector<string> re,temp;
  8. //threeOrFour:这个字符对应着几个字符;
  9. //ext:为了7(对应4个字符)以后的数字对应字符都+了1而定义的int,值是0或1
  10. int threeOrFour,ext;
  11. if(digits[len] == '7' || digits[len] == '9'){
  12. threeOrFour = 4;
  13. }else{
  14. threeOrFour = 3;
  15. }
  16. if(digits[len] > '7'){
  17. ext = 1;
  18. }else{
  19. ext = 0;
  20. }
  21. //ch是该数字对应的第一个字符
  22. char ch = (digits[len] - 48) * 3 + 91 + ext;
  23. string empty = "";
  24. if ( len < digits.size()){
  25. temp = combine(digits,len+1);
  26. }
  27. //递归的最底层
  28. if (len == digits.size() - 1){
  29. string t;
  30. for(int i = 0; i < threeOrFour; i++){
  31. t = empty;
  32. t.push_back(ch+i);
  33. re.push_back(t);
  34. }
  35. return re;
  36. }
  37. else{
  38. for (int i = 0; i < temp.size(); ++i){
  39. for(int j = 0; j < threeOrFour; j++){
  40. string str = empty;
  41. str.push_back(ch + j);
  42. re.push_back((str+temp[i]));
  43. }
  44. }
  45. return re;
  46. }
  47. }
  48. };

下面是修改之后,更加简洁的版本:

  1. class Solution {
  2. private:
  3. string letters[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
  4. public:
  5. vector<string> letterCombinations(string digits) {
  6. return Mycombine(digits,0);
  7. }
  8. vector<string> Mycombine(string digits,int len){
  9. std::vector<string> re, temp;
  10. temp.push_back("");
  11. if(digits.empty()) return re;
  12. if(len < digits.size() - 1){
  13. temp = Mycombine(digits,len+1);
  14. }
  15. string get = letters[toInt(digits[len])];
  16. for (int i = 0; i < temp.size(); ++i){
  17. for (int j = 0; j < get.size(); ++j){
  18. string put ="";
  19. put.push_back(get[j]);
  20. put += temp[i];
  21. re.push_back(put);
  22. }
  23. }
  24. return re;
  25. }
  26. int toInt(char ch){
  27. return ch - 48;
  28. }
  29. };

迭代方法:

  1. class Solution {
  2. private:
  3. string letters[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
  4. public:
  5. vector<string> letterCombinations(string digits) {
  6. std::vector<string> re,temp;
  7. if(digits.empty()) return re;
  8. re.push_back("");
  9. //temp.push_back("");
  10. for(int i = 0; i < digits.size(); i++){
  11. string get = letters[toInt(digits[i])];
  12. for(int j = 0; j < re.size(); j++){
  13. string t = re[j];
  14. for(int k = 0; k < get.size(); k++){
  15. string str = t;
  16. str.push_back(get[k]);
  17. temp.push_back(str);
  18. }
  19. }
  20. re = temp;
  21. temp.clear();
  22. }
  23. return re;
  24. }
  25. int toInt(char ch){
  26. return ch - 48;
  27. }
  28. };

事实上,用python的话非常好实现,而且逻辑很清晰:

  1. class Solution:
  2. def letterCombinations(self, digits):
  3. """
  4. :type digits: str
  5. :rtype: List[str]
  6. """
  7. if len(digits) == 0:
  8. return []
  9. re = ['']
  10. chars = ['','','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']
  11. m = {i:[ch for ch in chars[i]] for i in range(0,10)}
  12. data = [int(digits[i]) for i in range(len(digits)) ]
  13. for i in data:
  14. temp = []
  15. for s in re:
  16. for j in m[i]:
  17. temp.append(s + j)
  18. print(j)
  19. re = temp
  20. return re

[LeetCode]Letter Combinations of a Phone Number题解的更多相关文章

  1. LeetCode: Letter Combinations of a Phone Number 解题报告

    Letter Combinations of a Phone Number Given a digit string, return all possible letter combinations ...

  2. [LeetCode] Letter Combinations of a Phone Number 电话号码的字母组合

    Given a digit string, return all possible letter combinations that the number could represent. A map ...

  3. LeetCode——Letter Combinations of a Phone Number

    Given a digit string, return all possible letter combinations that the number could represent. A map ...

  4. [LeetCode] Letter Combinations of a Phone Number

    Given a digit string, return all possible letter combinations that the number could represent. A map ...

  5. [LeetCode] Letter Combinations of a Phone Number(bfs)

    Given a digit string, return all possible letter combinations that the number could represent. A map ...

  6. LeetCode Letter Combinations of a Phone Number (DFS)

    题意 Given a digit string, return all possible letter combinations that the number could represent. A ...

  7. [LeetCode] Letter Combinations of a Phone Number 回溯

    Given a digit string, return all possible letter combinations that the number could represent. A map ...

  8. LeetCode Letter Combinations of a Phone Number 电话号码组合

    题意:给一个电话号码,要求返回所有在手机上按键的组合,组合必须由键盘上号码的下方的字母组成. 思路:尼玛,一直RE,题意都不说0和1怎么办.DP解决. class Solution { public: ...

  9. leetcode Letter Combinations of a Phone Number python

    class Solution(object): def letterCombinations(self, digits): """ :type digits: str : ...

随机推荐

  1. zTree第一章,纯静态

    zTree v3.5 Demo 演示 http://www.treejs.cn/v3/demo.php#_101 ------------------------------------------- ...

  2. mysql 查看索引

    查看索引 mysql> show index from tblname; mysql> show keys from tblname; · Table 表的名称. · Non_unique ...

  3. 3分钟解决MySQL 1032 主从错误(转)

    转自  https://blog.51cto.com/suifu/1845457 3分钟解决MySQL 1032主从错误 Part1:写在最前 1032错误----现在生产库中好多数据,在从库误删了, ...

  4. jquery基础认知

    who      what触发       按钮      点击 (click)执行       div        动画 (animation) $(document).ready(functio ...

  5. set,env和export命令显示shell变量其区别,与环境变量扫盲(一)

    种类: ♦ set     :  用来显示本地变量,显示当前shell的变量,包括当前用户的变量 ♦ env    :  用来显示环境变量,显示当前用户的变量. ♦ export:  用来显示和设置环 ...

  6. socketserver模块解析

    socketserver模块是基于socket而来的模块,它是在socket的基础上进行了一层封装,并且实现并发等功能. 看看具体用法:       ​x         import sockets ...

  7. Bootstrap Table使用方法详解

    http://www.jb51.net/article/89573.htm bootstrap-table使用总结 bootstrap-table是在bootstrap-table的基础上写出来的,专 ...

  8. Working with Metal—Overview

    看完这个 WWDC 之后的总结. Metal 可以在单位时间内提供 10 倍的 draw call 调用. Background About Draw Call 每一次 draw call 调用都必须 ...

  9. 栈的理解和代码实现(java)

    从数据结构的角度来看,其实栈也是线性表.特殊性在于栈和队列的基本操作是线性表操作的子集,栈是操作受限制的线性表. 栈的定义 栈是限定仅在表尾进行插入或者删除操作的线性表.对于一个栈来说,表尾端有着特殊 ...

  10. SVN服务器端环境搭建步骤

    5.1 安装服务器端程序 yum install -y subversion 5.2 创建并配置版本库 创建版本库目录 mkdir -p /var/svn/repository 在版本库目录下创建具体 ...