给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
输入:"23" 输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
大致思路(三个版本
1. 第一想法是检索数字种类数目,然后输出
但是有的点没想到,有可能出现单独的数字
void letterCombinations(string digits)
{
vector<string> res;
int arr[9] = { 0,0,0,0,0,0,0,0,0 };
int count = 0;
//检测一共有多少种数字
for (int i = 0; i < digits.length() && count != 8; ++i)
{
if ((digits[i] - 48) >= 1 && (digits[i] - 48) <= 9)
{
arr[(digits[i] - 48) - 1]++;
if (arr[(digits[i] - 48) - 1] == 1)
count++;
}
}
string str[8] = { "abc","def","ghi","jkl","mno","pqrs","tuv","wxyz" };
for (int i = 0; i < 9; ++i)
{
string t = "";
if (arr[i] == 0)
continue;
for (int j = i + 1; j < 9; ++j)
{
if (arr[j] == 0)
continue;
for (int h = 0; h < str[i].length(); ++h)
{
for (int z = 0; z < str[j].length(); ++z)
{
t = "";
t += str[i - 1][h];
t += str[j - 1][z];
cout << t << endl;
}
}
}
}
return ;
}
2. 检索数字的种类,然后标记数字单个种类的数目,限制为2最大
解决了单个数字问题以及重复数字问题,但是新的问题出来了,数字的组合是不限制位数的,可能是三个的组合。
虽然可以根据count来暴力解决,但是不想做了已经(最大十八层循环,会死人的
此方法,原地爆炸。
class Solution {
public:
vector<string> letterCombinations(string digits)
{
vector<string> res;
int arr[10] = { 0,0,0,0,0,0,0,0,0 };
int count = 0;
//检测一共有多少种数字
for (int i = 0; i < digits.length() && count != 8; ++i)
{
if ((digits[i] - 48) >= 1 && (digits[i] - 48) <= 9)
{
if (arr[(digits[i] - 48)] != 2)
arr[(digits[i] - 48)]++;
if (arr[(digits[i] - 48)] == 1)
count++;
}
}
//构造一个全新的字符串
string numstr = "";
for (int i = 0; i < 10; ++i)
{
for (int j = 0; j < arr[i]; ++j)
numstr += (char)(i + 48);
}
string str[10] = { "","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz" };
if (count == 1 && numstr.length() == 1)
{
for (int i = 0; i < 10; ++i)
{
if (arr[i] == 0)
continue;
else
{
string t = "";
for (int j = 0; j < str[i].length(); ++j)
{
t = str[i][j];
res.push_back(t);
}
}
}
}
else
for (int i = 0; i < numstr.length(); ++i)
{
for (int j = i + 1; j < numstr.length(); ++j)
{
for (int h = 0; h < str[numstr[i] - 48].length(); ++h)
{
string t = "";
for (int z = 0; z < str[numstr[j] - 48].length(); ++z)
{
t = "";
t += str[numstr[i] - 48][h];
t += str[numstr[j] - 48][z];
res.push_back(t);
}
}
}
}
return res;
}
};
3. 看了一眼官方题解,有了个全排列的思路,但是又一想貌似又不对。
1. 有用树来解决排列组合问题的,但是复杂度太大了吧。
2. 还看到一个java的队列解法,但是没看懂。(https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/solution/javafei-chang-jing-qiao-de-dui-lie-jie-fa-by-xxxzz/)
3. c++的迭代解法(https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/solution/cdie-dai-by-yang-xin/)