[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

Spring AI + RAG 构建电商智能客服:从 PDF 文档解析到精准问答的全链路实战 核心框架:向量数据库:- PostgreSQL + pgvector (生产推荐)- Redis Stack (轻量级方案)- ChromaDB (快速原型)文档解析:- Apache PDFBox: PDF 文本提取- Spring AI Document Readers: 结构化解析大模型:- 阿里云百炼 (DashScope)- 本地部署:Qwen/ChatGLM/*** 电商领域实体*/@Data@Builder@ToString/*** 商品类型。 阅读详情

相关推荐

UFS 3.1协议实战解析:从MIPI M-PHY到SCSI命令的完整链路拆解

本文深入解析UFS 3.1存储协议,从MIPI M-PHY物理层到SCSI命令层,完整拆解数据链路。通过分析协议栈三层架构(UIC、UTP、UCS),结合Wireshark抓包实战,详解UPIU数据包传输与SCSI命令封装,并探讨GEAR模式对性能与功耗的影响,为嵌入式存储开发与调试提供实用指南。

weixin_29207533的博客 420

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

基于Landsat-8数据的山西省吕梁市地表温度反演研究过程(大气校正法)

1.数据下载:本实验采用的数据是 ①从地理空间数据云下载的来自landsat8 卫星,云量<=1%,时间为2017年5月12日的山西省吕梁市影像数据。为全面覆盖吕梁市,选用了两片影像。 ②吕梁市边界矢量图 2.数据预处理 ...

weixin_45747376的博客 6601

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

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

weixin_34306593的博客 811

【上海大学计算机组成原理实验报告】七、程序转移机制

学习实现程序转移的硬件机制//掌握堆栈寄存器的使用//手动方式实现子程序调用转移过程//手动方式实现子程序返回转移过程//编程实现`OUT`寄存器交替显示`11`和`55`//若要求`11`和`55`各显示`50`次后停机,应该如何修改程序?//根据实验指导书的相关内容,实验箱系统的程序转移硬件机制在于,当`LDPC`有效时,如果此时`DUBS`上的值就是转移的目标地址,则此目标地址被打入`PC`,从而实现程序的转移;若`LDPC`为`0`是附带条件的,就形成“条件转移”。

HackerKevon的博客 2473

HT7533与1117稳压芯片动态特性对比:实测分析与优化策略

本文深入对比了HT7533与1117稳压芯片的动态特性,包括电压过冲和瞬态响应能力,并提供了实测数据与优化策略。HT7533适合低功耗设备,而1117在大电流和稳定性要求高的场景表现更优。文章还分享了PCB布局和电容选择的实用建议,帮助工程师根据项目需求选择合适的稳压芯片。

weixin_28454475的博客 610

LeetCode 17. Letter Combinations of a Phone Number 题解

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

cannonjinx的博客 4387

KV Cache 详解:新手也能理解的 LLM 推理加速技巧

(Autoregressive)生成的,即每次生成一个 token,然后将其作为输入继续生成下一个 token。:如果序列太长,超过了 KV Cache 的存储限制,就需要丢弃最早的 tokens(类似滑动窗口)。时,每次只会生成一个新 token,然后再把这个 token 作为输入继续生成下一个 token。,只缓存计算过的 K,VK, V,每次只计算新 token 的 K,VK, V,从而提升推理效率。:如果输入的 prompt 发生变化,之前的 KV Cache 不能复用,必须重新计算。

Harry的博客 7356

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

GPU 运维实战:H100/H800/B300 换卡与压测

(烧多久、看什么、什么算合格)。文末还给了一个能直接跑的验收判定脚本,三个真实场景的裁决输出都在。

老韩的Linux云计算架构师进阶之路 270

开源Harness项目DeerFlow 2.0,让智能体几乎能完成任何复杂任务

从提示工程到上下文工程,再到如今的 Harness,这条演进路径的本质是从“教模型如何理解人类”迈向“为模型构建一个可执行、可信赖、可长期运转的数字世界”。 当越来越多像 DeerFlow 2.0 这样的 Super Agent Harness 走向普及,AI 将真正进化为能理解、会规划、可执行、敢交付、长期负责的成熟生产力形态。

技术引领业务创新 519

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

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

motongxue的博客 371

我终于停止写 JUnit 了!用 JavaParser + GPT-4 自动生成 90% 覆盖率的单元测试

本文介绍了一种基于JavaParser和GPT-4的智能单元测试生成方案。针对开发者在单元测试编写中面临的繁琐、无聊和硬指标等问题,提出通过AST语法树分析代码结构,提取关键信息后生成精准提示词,再调用GPT-4自动生成高质量的单元测试代码。文章详细阐述了技术原理、实现步骤(包括JavaParser解析、上下文感知提示词构建和GPT-4调用),并展示了该方法能自动识别依赖、Mock对象和覆盖边界条件,显著提升测试效率。同时指出了在复杂数据结构、私有方法测试等方面的局限性,最终强调这种技术组合可以解放开发者,

BUG猿的博客 1129

LeetCode 17. Letter Combinations of a Phone Number

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

wind_liang的博客 1080

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

[Java]LeetCode17 Letter Combinations of a Phone Number

[Java]LeetCode17 Letter Combinations of a Phone Number

fumier的专栏 1276

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

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

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

【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、付费专栏及课程。

余额充值