问题描述: 电话的号码盘上一个数字对应着几个字母,一串数字对应着几种字母的组合。 现在给定一组数字,列出对应的字母的组合。
思路: 例如:4对应键盘上
GHI, 2对应键盘上 ABC
数字 42 的组合对应的字符串,用树的表现形式:
42
4: G H I
2: A B A B A B
结果:GA, GB, HA, HB, IA, IB
代码:
#include <iostream>
using namespace std;
void func(int* number, int n)
{
int i = 0;
char c[10][10] = {
"*",
"#",
"ABC",
"DEF",
"GHI",
"JKL",
"MNO",
"PQRS",
"TUV",
"WXYZ",
};
int total[10] = {1,1,3,3,3,3,3,4,3,4};
int* answer = NULL;
answer = new int[n];
memset(answer, 0 , n*sizeof(int));
while (1)
{
cout << "[";
for (i = 0; i < n; i++)
{
cout << answer[i];
}
cout << "]" << endl;
for (i = 0; i < n; i++)
{
cout << c[number[i]][answer[i]];
}
cout << endl << endl;
int k = n-1;
while(k >= 0)
{
if (answer[k] < total[number[k]] - 1)
{
answer[k]++;
break;
}
else
{
answer[k] = 0;
k--;
}
}
if (k < 0)
break;
}
delete[] answer;
}
void main()
{
//int test[] = {1,2,3};
//int test[] = {5,6,7,8};
int test[] = {2,3,4};
int len = sizeof(test)/sizeof(test[0]);
func(test, len);
cin >> len;
}