1.描述
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) 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"].
来自 <https://leetcode.com/problems/letter-combinations-of-a-phone-number/>
2.分析
这个题目最好是使用递归或者回溯的方法,但是对这个方法不太熟悉,还是老老实实排列组合吧,最开始想到的是,遍历一遍数字,得到一张二维表,再对二维表进行处理,最后还是没想出来,然后就在稿纸上试着演算一下,找到了其中的规律。就写出下面的代码,其实也很容易理解。
不如输入23,
1读到2(代表abc)时,新建3个字符串,并分别将abc添加进去;
2接着读到3(def),根据def的长度是3,因此将1中的3个字符串扩展成3*3=9个字符串
3然后将def分别添加到这9个字符串的尾部,就得到了最终的组合:
a
b
c
扩展:
a
b
c
a
b
c
a
b
c
尾部添加:
ad
bd
cd
ae
be
ce
af
bf
cf
3.c++代码
//beats100%
vector<string> letterCombinations(string digits)
{
vector<string>res;
if (digits.empty())
return res;
string tmp="";
res.push_back("");
for (unsigned int i = 0; i < digits.size(); i++)
{
string s;
switch (digits[i])
{
case '0': {s = "0"; break; }
case '1': {s = "1"; break; }
case '2': {s = "abc"; break; }
case '3': {s = "def"; break; }
case '4': {s = "ghi"; break; }
case '5': {s = "jkl"; break; }
case '6': {s = "mno"; break; }
case '7': {s = "pqrs"; break; }
case '8': {s = "tuv"; break; }
case '9': {s = "wxyz"; break; }
case '*': {s = "*"; break; }
case '#': {s = "*"; break; }
}
vector<string>tt = res;
for (unsigned int j = 0; j < s.size()-1; j++)
{
if(i==0)
res.push_back("");
else
res.insert(res.end(), tt.begin(), tt.end());
}
for (unsigned int j = 0; j < res.size(); j++)
{
int index = j / (res.size()/s.size());
res[j] += s[index];
}
}
return res;
}
代码中有几个需要注意的地方:
1.关于扩展数组长度
刚开始res.push_back("");,即将结果长度置为1,这样便于更新读取第一个数字跟新长度,比如读取的第一个数字是2(abc),就将res长度扩展成3,下一次读到3(def),将长度为3的res更新为长度9的res;
vector<string>tt = res;
for (unsigned int j = 0; j < s.size()-1; j++)
{
if(i==0)
res.push_back("");
else
res.insert(res.end(), tt.begin(), tt.end());
}
首先复制当前的res到tt
然后更新长度使用vector内置的insert插入的方法,将tt插入到res的尾部n-1次(n是当前数字代表的字符串的长度)
其中vector的insert接受三个参数,第一个是被插入的vector的位置,这里选的尾部res.end(),后面两个参数是插入的vector的范围,选择整个插入(tt.begin(), tt.end())。
这里i==0比较特殊,因为res.insert(res.end(), tt.begin(), tt.end());不允许tt是空的,因此第一次更新时特殊处理。
2.尾部添加的字符的下标更新方法
在扩展数组长度完成后,需要在尾部添加当前数字对应的字符,根据上面的演算,比如上次的res长度是9,这次读进来的数字代表长度为3,那么需要将res长度扩大3倍,即当前res是[res_1][res_2][res+3],然后即将三个字母分别添加到res_1、res_2、res_3尾部。
代码中res.size()/s.size()的结果实际就是上一次res的长度==res_1、res_2、res_3的长度
for (unsigned int j = 0; j < res.size(); j++)
{
int index = j / (res.size()/s.size());
res[j] += s[index];
}
参考:
两个 vector 怎么合并?
https://blog.youkuaiyun.com/cau_eric/article/details/26011627