2014-05-02 10:07
原题:
Mapping
'' = 'A','B','C'
'' = 'D','E','F'
...
'' = input:
output :ouput = [AAD, BBD, CCD, AAE, AAF, BBE, BBF, CCE, CCF]
题目:电话的数字按键和字母有个映射关系,给定一串数字,请给出所有可能的字符映射方式。
解法:此人也不给个描述,搞的下面一堆人来猜题意。这个题目的意思是说,对于给定的数字串,有多少种不同的映射方式。像“112” -> “ABD”这样是不允许的,因为“1”只能表示一种字母,不能同时表示“A”和“B”。
代码:
// http://www.careercup.com/question?id=5765850736885760
#include <iostream>
#include <string>
#include <vector>
using namespace std; void DFS(int idx, vector<pair<int, char> > &dict, vector<string> &result, const string &s)
{
int i; if (idx == (int)dict.size()) {
static char m[]; for (i = ; i < (int)dict.size(); ++i) {
m[dict[i].first] = dict[i].second;
} static string res; res.clear();
for (i = ; i < (int)s.length(); ++i) {
res.push_back(m[s[i] - '']);
} result.push_back(res);
return;
} switch(dict[idx].first) {
case :
case :
case :
case :
case :
case :
case :
case :
for (i = ; i < ; ++i) {
dict[idx].second = (dict[idx].first * + i) + 'A';
DFS(idx + , dict, result, s);
}
break;
case :
for (i = ; i < ; ++i) {
dict[idx].second = (dict[idx].first * + i) + 'A';
DFS(idx + , dict, result, s);
}
break;
}
} int main()
{
int i;
string s;
vector<pair<int, char> > dict;
vector<string> result;
int a[]; while (cin >> s) {
for (i = ; i < ; ++i) {
a[i] = ;
}
for (i = ; i < (int)s.length(); ++i) {
a[s[i] - ''] = ;
} for (i = ; i < ; ++i) {
if (a[i]) {
dict.push_back(make_pair(i, '\0'));
}
} DFS(, dict, result, s);
cout << "{" << endl;
for (i = ; i < (int)result.size(); ++i) {
cout << " " << result[i] << endl;
}
cout << "}" << endl; dict.clear();
result.clear();
} return ;
}