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实现的代码,非递归,非常简单。

class Solution {
public:
vector<string> letterCombinations(string digits) {
return combine(digits,0);
}
std::vector<string> combine(string digits,int len){ vector<string> re,temp;
//threeOrFour:这个字符对应着几个字符;
//ext:为了7(对应4个字符)以后的数字对应字符都+了1而定义的int,值是0或1
int threeOrFour,ext;
if(digits[len] == '7' || digits[len] == '9'){
threeOrFour = 4;
}else{
threeOrFour = 3;
}
if(digits[len] > '7'){
ext = 1;
}else{
ext = 0;
}
//ch是该数字对应的第一个字符
char ch = (digits[len] - 48) * 3 + 91 + ext;
string empty = ""; if ( len < digits.size()){
temp = combine(digits,len+1);
} //递归的最底层
if (len == digits.size() - 1){
string t;
for(int i = 0; i < threeOrFour; i++){
t = empty;
t.push_back(ch+i);
re.push_back(t);
}
return re;
}
else{
for (int i = 0; i < temp.size(); ++i){
for(int j = 0; j < threeOrFour; j++){
string str = empty;
str.push_back(ch + j);
re.push_back((str+temp[i]));
}
}
return re;
}
} };

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

class Solution {
private:
string letters[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public:
vector<string> letterCombinations(string digits) {
return Mycombine(digits,0);
}
vector<string> Mycombine(string digits,int len){
std::vector<string> re, temp;
temp.push_back("");
if(digits.empty()) return re;
if(len < digits.size() - 1){
temp = Mycombine(digits,len+1);
} string get = letters[toInt(digits[len])];
for (int i = 0; i < temp.size(); ++i){
for (int j = 0; j < get.size(); ++j){
string put ="";
put.push_back(get[j]);
put += temp[i];
re.push_back(put);
}
}
return re; }
int toInt(char ch){
return ch - 48;
}
};

迭代方法:

class Solution {
private:
string letters[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public:
vector<string> letterCombinations(string digits) {
std::vector<string> re,temp;
if(digits.empty()) return re;
re.push_back("");
//temp.push_back("");
for(int i = 0; i < digits.size(); i++){
string get = letters[toInt(digits[i])];
for(int j = 0; j < re.size(); j++){
string t = re[j];
for(int k = 0; k < get.size(); k++){
string str = t;
str.push_back(get[k]);
temp.push_back(str);
}
}
re = temp;
temp.clear();
}
return re;
} int toInt(char ch){
return ch - 48;
}
};

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

class Solution:
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if len(digits) == 0:
return []
re = ['']
chars = ['','','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']
m = {i:[ch for ch in chars[i]] for i in range(0,10)} data = [int(digits[i]) for i in range(len(digits)) ] for i in data:
temp = []
for s in re:
for j in m[i]:
temp.append(s + j)
print(j)
re = temp 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. js正则包含三位

    var reg = new RegExp("^(?![A-Za-z]+$)(?![A-Z\\d]+$)(?![A-Z_\\W]+$)(?![a-z\\d]+$)(?![a-z_\\W]+$) ...

  2. samba服务器的安装与配置(之前是因为没有把共享文件权限放开!)(windows7和centOS6)

    注:centOS6跟centOS7安装方法不一样哦.以下是centOS6的安装过程. 安装:yum -y install samba 启动:/etc/init.d/smb start 设置开机启动:c ...

  3. python 爬恶魔法则(单线程卡成狗)

    from bs4 import BeautifulSoupimport requestsimport sysclass down(object): def __init__(self): self.n ...

  4. c++之函数形参和实参

    c++之函数形参和实参讲解 1.非地址型参数 在c++中实现模块化编程时,我们形成会遇到对自定义的函数模块传入参数的操作,即形参.这里主要讲解一个非地址型的形参. 不多说,先看代码: #include ...

  5. 论文笔记:CNN经典结构2(WideResNet,FractalNet,DenseNet,ResNeXt,DPN,SENet)

    前言 在论文笔记:CNN经典结构1中主要讲了2012-2015年的一些经典CNN结构.本文主要讲解2016-2017年的一些经典CNN结构. CIFAR和SVHN上,DenseNet-BC优于ResN ...

  6. 部署WSUS服务(一)

    引言:随着网络的发展,我们的生活也越来越离不开网络,但面临的安全威胁也越来越多.像去年爆发的针对Windows系统的勒索病毒(Wanna Cry)和年初爆发的Intel芯片漏洞告诉我们网络威胁时时刻刻 ...

  7. leetcode-201-数字范围按位与

    题目描述: 给定范围 [m, n],其中 0 <= m <= n <= 2147483647,返回此范围内所有数字的按位与(包含 m, n 两端点). 示例 1: 输入: [5,7] ...

  8. c#-MVC基础操作-数据的展示及增删改、登录页面及状态保持

    一.数据展示 1.View代码: <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynam ...

  9. (C/C++) 指向函數的指標

    最近再跟指標做朋友, 正好遇到函數與指標. 其實函數也在程式內也是有屬於自己的位址 所以指標一樣能指向函數, 在此釐清自己的觀念以及記錄下來. #include <stdio.h> #in ...

  10. xilinx DMA IP核(二) —— 文档阅读

    本笔记不记录DMA的Scatter/Gather特性.DMA上有三种总线:AXI4-LIte(对寄存器进行配置),AXI4-Memory Map(用于与内存交互)和AXI4 Stream(用于与外设交 ...