热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

电话号码的字母组合解题思路和代码示例

本文介绍了力扣题目《电话号码的字母组合》的解题思路和代码示例。通过使用哈希表和递归求解的方法,可以将给定的电话号码转换为对应的字母组合。详细的解题思路和代码示例可以帮助读者更好地理解和实现该题目。

题目描述

在这里插入图片描述

解题思路

在这里插入图片描述

代码示例


class Solution
{
public:vector<string> letterCombinations(string digits) {vector<string> combinations;//用来存放组合结果的解集if (digits.empty()) //如果输入为空&#xff0c;直接返回{return combinations;}unordered_map<char, string> phoneMap//建立哈希表{{&#39;2&#39;, "abc"},{&#39;3&#39;, "def"},{&#39;4&#39;, "ghi"},{&#39;5&#39;, "jkl"},{&#39;6&#39;, "mno"},{&#39;7&#39;, "pqrs"},{&#39;8&#39;, "tuv"},{&#39;9&#39;, "wxyz"}};string combination;//存放部分解backtrack(combinations, phoneMap, digits, 0, combination);//递归求解return combinations;}void backtrack(vector<string>& combinations, const unordered_map<char, string>& phoneMap, const string& digits, int index, string& combination) //将部分解按地址传入&#xff0c;避免重复拷贝{if (index &#61;&#61; digits.length()) //递归出口{combinations.push_back(combination);//组合好的解插入结果解集中} else {char digit &#61; digits[index];const string& letters &#61; phoneMap.at(digit);//at 查找key所对应的值&#xff0c;如果存在&#xff1a;返回key对应的值&#xff0c;可以直接修改&#xff0c;和[]操作一样。如果不存在&#xff1a;抛出 out_of_range 异常.for (const char& letter: letters) {combination.push_back(letter);//插入字符backtrack(combinations, phoneMap, digits, index &#43; 1, combination);//递归combination.pop_back();//将组合完的解从部分解中去除}}}
};

力扣


推荐阅读
author-avatar
崔颖2849464
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有