这也是一道很常见的题目,好多类似的题目用的也是同样的解法,这道题目的意思是,我们的手机上的数字键上面对应着英文字母,那么这个数字可能对应3个,也可能对应4个,也有可能对应0个,那么,当我输入一串数字后,需要给出所有这些数字可能对应的英文字母。
说到这里,相信大家也就明白了,这其实就是全排列,只不过我们首先需要给出已知条件,即数字对应着哪些字母,对应着几个字母,因为要做全排列,就一定要知道一个范围,所以,利用全排列的思想,我们很容易写出如下的代码:
函数声明:
/*3.2 电话号码对应英语字母*/ void DutNumberToAlphabet(int*, int); void DutNumberToAlphabet(int*, int, char*, int, int*);
源代码:
char c[][10] = {"","","ABC","DEF","GHI","JKL","MNO","PQRS","TUV","WXYZ"};//存储各个数字所能代表的字符 int total[10] = {0, 0, 3, 3, 3, 3, 3, 4, 3, 4}; //各个数组所能代表的字符总数 void DutNumberToAlphabet(int* number, int size) { if (!number || size <= 0) return; char* result = new char[size]; int* answer = new int[size]; memset(answer, 0, sizeof(int) * size); DutNumberToAlphabet(number, size, result, /*index*/0, answer); } void DutNumberToAlphabet(int* number, int size, char* result, int index, int* answer) { if (index == size) { for (int i = 0; i < size; ++i) cout << c[number[i]][answer[i]]; cout << endl; } else { for (answer[index] = 0; answer[index] < total[number[index]]; ++answer[index]) DutNumberToAlphabet(number, size, result, index + 1, answer); } }
原文地址:http://blog.csdn.net/dlutbrucezhang/article/details/40261775