题目描述:
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
解题方案:
这道题也没有什么难点,我是写了一个子函数,输入数字,将对应的字母存在向量里返回,回溯的时候遍历就可以了。
代码:
#include <iostream>
#include <string>
#include <string.h>
#include <vector>
#include <algorithm>
#include <iostream>
#include <set>
#include <algorithm>
#include <sstream>
#include <queue>
#include <iomanip>
using namespace std;
vector<char> getDigit(char num)
{
vector<char> char_tmp;
if (num == '2')
{
char_tmp.push_back('a');
char_tmp.push_back('b');
char_tmp.push_back('c');
} else if (num == '3')
{
char_tmp.push_back('d');
char_tmp.push_back('e');
char_tmp.push_back('f');
} else if (num == '4')
{
char_tmp.push_back('g');
char_tmp.push_back('h');
char_tmp.push_back('i');
} else if (num == '5')
{
char_tmp.push_back('j');
char_tmp.push_back('k');
char_tmp.push_back('l');
} else if (num == '6')
{
char_tmp.push_back('m');
char_tmp.push_back('n');
char_tmp.push_back('o');
} else if (num == '7')
{
char_tmp.push_back('p');
char_tmp.push_back('q');
char_tmp.push_back('r');
char_tmp.push_back('s');
} else if (num == '8')
{
char_tmp.push_back('t');
char_tmp.push_back('u');
char_tmp.push_back('v');
} else if (num == '9')
{
char_tmp.push_back('w');
char_tmp.push_back('x');
char_tmp.push_back('y');
char_tmp.push_back('z');
}
return char_tmp;
}
void getResult(string inStr, int start, string temp, vector<string>& result)
{
if (temp.length() == inStr.length())
{
result.push_back(temp);
} else {
vector<char> let = getDigit(inStr[start]);
for (int i = 0; i < let.size(); i++)
{
temp.append(1, let[i]);
getResult(inStr, start + 1, temp, result);
temp.pop_back();
}
}
}
int main()
{
vector<vector<char>> dict;
vector<char> char_tmp;
char tmp;
string inStr;
vector<string> result;
string temp;
getline(cin, inStr);
if (inStr.length() == 0)
{
return 0;
}
getResult(inStr, 0, temp, result);
cout << "[";
for (int i = 0; i< result.size(); i++)
{
for (int j = 0; j < result[i].size(); j++)
{
cout << result[i][j];
}
if (i != result.size() - 1)
{
cout << ",";
}
}
cout << "]" << endl;
return 0;
}
参考:
[1] https://blog.csdn.net/rabbitsockx/article/details/85172362