[LeetCode] 17. Letter Combinations of a Phone Number

LeetCode 17. Letter Combinations of a Phone Number--输入数字,每个数字对应手机键盘的字符,输出组合的字符串-非递归实现 LeetCode 17. 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 st 阅读详情

Letter Combinations of a Phone Number

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.
在这里插入图片描述

解析

2-9分别可以表示各自的字符,输入一个包含2-9字符的字符串,输出所有可能表示的字符串。

自己写的

用一个map来保存数字字符对应的string,建立一个函数用于递归,当输入字符为空时,说明递归了所有的字符长度,关键在于每次递归之后要将当前最后一个字符去掉。

class Solution {
public:
    void recursive(string s, vector<string>& v, map<char,string>& digit,string &res){
        if(s.size()==0){
            cout<<"push: "<<res<<endl; 
            v.push_back(res);
        }
        for(int i=0;i<digit[s[0]].size();i++){
            res += digit[s[0]][i];
            cout<<digit[s[0]]<<" "<<res<<endl;
            recursive(s.substr(1), v, digit,res);
            res = res.substr(0,res.size()-1);
        }
    }
    vector<string> letterCombinations(string str) {
        vector<string> v;
        int size = str.size();
        if(size==0)
            return v;
        map<char, string> digit;
        digit['2'] = "abc";digit['3'] = "def";
        digit['4'] = "ghi";digit['5'] = "jkl";
        digit['6'] = "mno";digit['7'] = "pqrs";
        digit['8'] = "tuv";digit['9'] = "wxyz";
        string res ="";
        recursive(str, v, digit,res);
        return v;
    }
};

递归

使用一个index来表示当前递归的位置,当index=输入字符串长度时结束调用。

class Solution {
public:
    void recursive(string s, vector<string>& v, string digit[],string &res,int index){
        if(index == s.size()){
            cout<<"push: "<<res<<endl; 
            v.push_back(res);
            return;
        }
        for(int i=0;i<digit[s[index]-'0'].size();i++){
            res += digit[s[index]-'0'][i];
            recursive(s, v, digit,res,index+1);
            res = res.substr(0,res.size()-1);
        }
        
    }
    vector<string> letterCombinations(string str) {
        vector<string> v;
        int size = str.size();
        if(size==0)
            return v;
        string digit[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        string res ="";
        recursive(str, v, digit,res,0);
        return v;
    }
};

迭代

取当前数字代表的字符,然后遍历字符大小,并遍历已有的res字符,将当前单个字符加在后面,遍历一遍之后交换。
下面给出一个参考例子

Explanation with sample input “234”
Initial state:
result = {""}
Stage 1 for number “2”:
result has {""}
candiate is “abc”
generate three strings “” + “a”, “”+“b”, “”+“c” and put into tmp,
tmp = {“a”, “b”,“c”}
swap result and tmp (swap does not take memory copy)
Now result has {“a”, “b”, “c”}

Stage 2 for number “3”:
result has {“a”, “b”, “c”}
candidate is “def”
generate nine strings and put into tmp,
“a” + “d”, “a”+“e”, “a”+“f”,
“b” + “d”, “b”+“e”, “b”+“f”,
“c” + “d”, “c”+“e”, “c”+“f”
so tmp has {“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf” }
swap result and tmp
Now result has {“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf” }

Stage 3 for number “3”:
result has {“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf” }
candidate is “ghi”
generate 27 strings and put into tmp,
add “g” for each of “ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”
add “h” for each of “ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”
add “h” for each of “ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”
so, tmp has
{“adg”, “aeg”, “afg”, “bdg”, “beg”, “bfg”, “cdg”, “ceg”, “cfg”
“adh”, “aeh”, “afh”, “bdh”, “beh”, “bfh”, “cdh”, “ceh”, “cfh”
“adi”, “aei”, “afi”, “bdi”, “bei”, “bfi”, “cdi”, “cei”, “cfi” }
swap result and tmp
Now result has
{“adg”, “aeg”, “afg”, “bdg”, “beg”, “bfg”, “cdg”, “ceg”, “cfg”
“adh”, “aeh”, “afh”, “bdh”, “beh”, “bfh”, “cdh”, “ceh”, “cfh”
“adi”, “aei”, “afi”, “bdi”, “bei”, “bfi”, “cdi”, “cei”, “cfi” }
Finally, return result.

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        if (digits.empty()) return {};
        vector<string> res{""};
        string dict[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        for (int i = 0; i < digits.size(); ++i) {
            int num = digits[i]-'0';
            if(num < 0 || num > 9) break;
            string str = dict[num];
            vector<string> tmp;
            for (int j = 0; j < str.size(); ++j) {
                for(int k=0; k<res.size(); k++){
                    tmp.push_back(res[k] + str[j]);
                }
            }
            res = tmp;
        }
        return res;
    }
};

参考

http://www.cnblogs.com/grandyang/p/4452220.html
https://leetcode.com/problems/letter-combinations-of-a-phone-number/discuss/8090/Iterative-c%2B%2B-solution-in-0ms

cosi-corr操作详细步骤 cosi-corr是一个可以加载到ENVI的软件包,由加利福尼亚理工学院的François Ayoub,  Sébastien Leprince,  and Lionel Keene开发,并且提供源代码,该软件受到了NSF的资助。软件的主要功能是可以满足各种影响的正射校正和影像配准。 针对下载下来的软件包参考《cosi-corr_guide.pdf》,进行配置使用具体详细过程如下: (本机环境 阅读详情

相关推荐

在摩尔线程 MTT S80 上使用 Ollama 进行 DeepSeek R1 蒸馏版模型推理

本文主要介绍了如何在摩尔线程 MTT S80 上通过 Ollama 快速完成DeepSeek R1 蒸馏系列模型的推理。

摩尔线程blog中心 3598

LeetCode解题报告--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:D

gannyee 2688

面向网络攻击行为可视化分析系统实现【WebSocket + 可视化】

本系统主要应用于网站运维管理,它解决了网站运维人员排查网络攻击行为复杂且繁琐等问题,提高了运维人员网络安全分析的效率和准确性。

oNew_Lifeo的博客 1620

即梦AI替代工具全测评:4款方案实测对比与选型指南

在人工智能生成内容领域,AI绘画与视频工具不断涌现,其底层原理多基于扩散模型与多模态预训练技术,技术价值在于降低创作门槛、提升产出效率。随着应用场景从灵感草稿延伸到商业成片,创作者对工具的功能覆盖和生成稳定性提出了更高要求。针对这一趋势,不少用户开始寻找即梦AI的替代工具。本文从实际需求出发,统一创作条件,对4款主流方案进行统一试跑实测,围绕生成质量、响应速度、操作体验等维度展开对比,并总结选型思路与实操避坑经验,为需要构建高效AI创作流程的团队和个人提供参考依据。

weixin_34306593的博客 811

Apache Flink集成HDFS报错Failed to create checkpoint storage at checkpoint coordinator side.

在网上查询相关资料后,在flink的lib目录添加flink-shaded-hadoop-3-3.1.1.7.0.3.0-79-7.0.jar、commons-cli-1.5.0.jar两个包,但报错依旧存在,添加了export HADOOP_CLASSPATH=后面发现是hadoop与flink的兼容性问题,hadoop原先使用的是3.3.4,与多个版本的flink集成都会出现报错,最后将Hadoop的版本改成3.1.3,使用flink run运行jar包就没有这个错误了,在hdfs上成功保存了检查点。

zywenmag的博客 623

2024东南大学533复试C++程序设计笔试真题精讲

【东南553复试C++】2024东南大学533复试C++程序设计笔试真题精讲

转遍世界 3415

LeetCode 17. Letter Combinations of a Phone Number 题解

本题是回溯算法的经典问题,主要考察对回溯思想的理解和应用。通过维护一个路径数组和索引,我们可以生成所有可能的字母组合。回溯算法的核心思想是:通过选择、递归、回溯的过程,遍历所有可能的解空间,找到符合条件的解。建立数字到字母的映射表,方便快速查找每个数字对应的字母。当处理完所有数字时,将当前组合添加到结果中。对于每个数字,遍历其对应的所有字母,递归生成组合。这种方法不仅适用于电话号码的字母组合问题,还可以应用于许多其他组合问题,例如排列问题、组合问题等。

cannonjinx的博客 4387

极空间NAS小白也能搞定的Gitea部署:Docker+MySQL避坑全记录

本文为极空间NAS用户提供了一份详尽的Gitea私有代码仓库部署指南。针对极空间ARM架构和图形化Docker管理的特殊性,文章重点讲解了如何通过Docker和MySQL容器进行部署,并提供了三种获取兼容镜像的实战策略,特别是利用第三方镜像站转录的方法,帮助小白用户成功搭建并初始化Gitea服务,实现私有Git托管。

weixin_28318011的博客 366

LeetCode算法题之17. Letter Combinations of a Phone Number(medium)

题目描述: 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) i...

DaMoWangZQ的博客 309

RK3568 OpenHarmony3.2 NFC 驱动适配(PN7150)II

承接上文《RK3568 OpenHarmony3.2 NFC 驱动适配(PN7150)I》,继续PN7150 NFC模块的整体适配。本文主要介绍包括HDI实现层、框架层以及设备适配层的代码修改思路。具体包括vendor_adaptor、hdi_service等;以及foundation下的frameworks、services等。此外还包括相关三方库libnfc-nci在鸿蒙平台的移植和适配。需要注意的是,当前nfc适配只是基于作者手上的RK3568平台以及相关OpenHarmony3.2的代码。

Martian_Jonas的博客 1360

C语言程序设计——单词的统计和替换

【任务描述】 对任意一篇英文文章,统计其中每个单词分别出现了多少次,并可替换指定的单词。⑶ 对单词进行替换时,允许用户选择全部替换或逐个替换。替换完成后,将文章保存到文件。⑴ 英文文章以文件形式输入。⑵ 统计的结果保存到文件。

m0_60738889的博客 810

LeetCode 力扣 17. 电话号码的字母组合 letter combinations of a phone number

大家觉得写还可以,可以点赞、收藏、关注一下吧! 也可以到我的个人博客参观一下,估计近几年都会一直更新!和我做个朋友吧!https://motongxue.cn 文章目录17. 电话号码的字母组合题目描述示例:说明:分析StringStringBuilder优化运行结果 17. 电话号码的字母组合 题目描述 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。 示例: 输入:"23" 输出:["ad", "ae", "af

motongxue的博客 371

Open3D——平面点云凸多边形轮廓提取【2025最新版】

平面点云凸多边形轮廓提起,博客长期更新,本文最近更新时间为:2025年1月6日。

点云侠的博客 6753

LeetCode 17. Letter Combinations of a Phone Number

题目描述(中等难度) 给一串数字,每个数可以代表数字键下的几个字母,返回这些数字下的字母的所有组成可能。 解法一 定义相乘 自己想了用迭代,用递归,都理不清楚,灵机一动,想出了这个算法。 把字符串 "23" 看成 ["a","b",c] * ["d","e","f"] ,而相乘就用两个 for 循环实现即可,看代码应该就明白了。 public List<String> letter...

wind_liang的博客 1080

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

[Java]LeetCode17 Letter Combinations of a Phone Number

[Java]LeetCode17 Letter Combinations of a Phone Number

fumier的专栏 1276

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

Leetcode17. Letter Combinations of a Phone Number

Leetcode17. Letter Combinations of a Phone Number 写在前头:本人C++功底比较差,拿leetcode练C++,大佬莫笑。 输入2-9,返回所有可能的字符串 递归和迭代 这个题里面,迭代就像树的层次遍历,一行一行的出,出一个,把它子节点全push进来,直到最后一行为止全是子节点,ok了 先找[“a”“b”“c”] 递归的思想类似深度遍历,一直往下...

这里只有黑里 167

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

【DFS】LeetCode 17. Letter Combinations of a Phone Number

LeetCode 17. Letter Combinations of a Phone Number Solution1:我的答案 利用8皇后同样的方法,回溯+递归 class Solution { public: vector&amp;amp;amp;amp;amp;amp;lt;string&amp;amp;amp;amp;amp;amp;gt; letterCombinations(string digits) { if (digits.size()

Allenlzcoder的博客 294

Leetcode 17 Letter Combinations of a Phone Number

题意为输出所有按键可能表示的字母组合。 因为不知道按键组合有多长,所以可以用搜索来做, 为了效率我用的是BFS,不过好像也没快到哪里去。 先打印出字典表,用队列进行搜索,算法的复杂度最优就行了,不必在意常数项的问题。

无名山丘,崛起成峰 4380

【LeetCode】17.Letter Combinations of a Phone Number(medium)

【LeetCode】17.Letter Combinations of a Phone Number(medium)解题报告 题目地址:https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/ 题目描述:   Given a digit string, return all poss

郝春雨的博客 306

Leetcode 17. Letter Combinations of a Phone Number

https://leetcode.com/problems/letter-combinations-of-a-phone-number/ class Solution { public: string mapping[8]={"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; void get_string(string &amp...

weixin_34005042的博客 171

【Leetcode】17. Letter Combinations of a Phone Number

题目地址: https://leetcode.com/problems/letter-combinations-of-a-phone-number/ 给定一个由数字组成的字符串,返回其在电话号码盘上代表的所有字符串。很经典的DFS题,要遵循做当前的选择,枚举下一个选择,撤销当前的选择,这样的步骤。同时注意一下枚举结束的条件。此问题枚举结束当且仅当枚举到digits最后一位。代码如下: import...

数学、算法爱好者的博客 253

[LeetCode 17] Letter Combinations of a Phone Number

题目链接:letter-combinations-of-a-phone-number import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Given a digit string, return all possible letter combinations tha

瓦尔登湖 909

17. Letter Combinations of a Phone Number Leetcode Python

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. Inpu

hyperbolechi的专栏 2062
上一篇: [LeetCode] 18. 4Sum
下一篇: [LeetCode] 22. Generate Parentheses
Peng_maple
博客等级 码龄10年 0粉丝 79原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值