博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 17. Letter Combinations of a Phone Number
阅读量:3711 次
发布时间:2019-05-21

本文共 1805 字,大约阅读时间需要 6 分钟。

LeetCode 17. Letter Combinations of a Phone Number


最近在做LeetCode中的题,第一次更C++和算法系列文章就拿这道题开张吧。

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.

在这里插入图片描述

Example:

Input: “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.

首先看到这道题,感觉无从下手,我也是这种心理,怎么下手呀,喜欢百度,好吧原谅我做的题少,找了几个版本,找到这一版的,感觉讲解的非常清晰。

参考:

枚举所有情况:

对每一个输入数字,对于已有的排列中的每一个字符串,分别加入该数字所代表的每一个字符。
到这里想到了什么,对三重for循环。
举例:
初始化排列{""} //空的容器
1、输入 2 ;
此时已有的排列是 “” 空的字符串,得到{“a”,“b”,“c”}
2、输入3;
遍历已有的排列中的每一个字符串,则:
1>对于"a", 删除"a",加入’d’,‘e’,‘f’,得到{“b”,“c”,“ad”,“ae”,“af”}
2>对于"b",删除"b",加入’d’ ,‘e’, ‘f’,得到{“c” , “ad” ,“ae” ,“af” ,“bd”, “be”, “bf”}
3>同理 删除 “c”, 加入’d’, ‘e’, ‘f’ ,得到 {“ad”,“ae”,“af”,“bd”,“be”,“bf”,“cd”,“ce”,“cf”}
注意:
1.每次添加新字母时,应该先取vector变量ret的size(),遍历此大小即可,因为ret vertor变量是变化的。
2.删除vector首元素代码为:

ret.erase(ret.begin());

介于c++解决此类算法题最常用的就是vector和string对象。后面我会专门开辟系列文章学习这两个对象。

class Solution {public:	vector
letterCombinations(string digits){ vector
ret; if(digits == "") { return ret; } ret.push_back(""); //初始化 {""} vector
dict(10); //初始化大小为10的词典 0--9 dict[2] = "abc"; dict[3] = "def"; dict[4] = "ghi"; dict[5] = "jkl"; dict[6] = "mno"; dict[7] = "pqrs"; dict[8] = "tuv"; dict[9] = "wxyz"; for(int i = 0; i < digits.size(); i++) { int size = ret.size(); for(int j = 0; j < size; j++) { string cur = ret[0]; ret.erase(ret.begin()); for(int k = 0; k < dict[digits[i] - '0'].size(); k++) { ret.push_back(cur + dict[digits[i] - '0'][k]); } } } return ret; }};

转载地址:http://dkzjn.baihongyu.com/

你可能感兴趣的文章
关于String==和String.intern()的面试题,一文读懂
查看>>
new Hashmap 和 new ArrayList时设置初始化容量多少合适
查看>>
RocketMQ概念简介
查看>>
关于BIO和NIO的理解与总结(网络IO)
查看>>
STL应用之stack、queue、priority_queue容器适配器
查看>>
继承的学习——C++
查看>>
实现一个minishell小程序
查看>>
设计模式(单例模式)——Linux系统编程
查看>>
网络基础1(协议、协议模型、IP、Port、网络字节序)——Linux网络编程
查看>>
网络基础2(ARP、NAT、DNS协议)——Linux网络编程
查看>>
UDP、TCP协议——Linux网络编程
查看>>
HTTP、HTTPS协议——Linux网络编程
查看>>
string类——C++
查看>>
SpringMVC入门(springMVC的环境配置和入门程序以及简单的流程)
查看>>
PigyChan_LeetCode 725. 分隔链表
查看>>
PigyChan_LeetCode 面试题 02.08. 环路检测
查看>>
PigyChan_LeetCode 109. 有序链表转换二叉搜索树
查看>>
PigyChan_LeetCode 143. 重排链表
查看>>
PigyChan_LeetCode 24. 两两交换链表中的节点
查看>>
PigyChan_LeetCode 445. 两数相加 II
查看>>