标签:
题目:
电话的号码盘一般可以用于输入字母,如用2可以输入A,B,C,用3可以输入D,E,F等,对于号码5869872可以依次输出其代表的所有的字母组合。
解法一:直接循环法:
#include<iostream> #include<stdio.h> using namespace std; #define TelLength 3 int main() { char c[10][10]= { "", //0 "", //1 "ABC", //2 "DEF", //3 "GHI", //4 "JKL", //5 "MNO", //6 "PQRS", //7 "TUV", //8 "WXYZ" //9 }; int total[10] = {0,0,3,3,3,3,4,3,4}; int number[TelLength] = {4,2,7}; int answer[TelLength] = {0,0,0}; cout << "427" << "对应的所有英文是:\n"; for(answer[0] = 0; answer[0] < total[number[0]]; answer[0] ++) for(answer[1] = 0; answer[1] < total[number[1]]; answer[1] ++) for(answer[2] = 0; answer[2] < total[number[2]]; answer[2] ++) { for(int i = 0; i < TelLength; i ++) cout << c[number[i]][answer[i]]; cout << "\n"; } getchar(); return 0; }以上代码是三级的循环,如果多四级或5级的呢,那再加循环,太麻烦了。
来看下面的一种解法。
#include<iostream> #include<stdio.h> using namespace std; #define TelLength 3 int main() { char c[10][10]= { "", //0 "", //1 "ABC", //2 "DEF", //3 "GHI", //4 "JKL", //5 "MNO", //6 "PQRS", //7 "TUV", //8 "WXYZ" //9 }; int total[10] = {0,0,3,3,3,3,4,3,4}; int number[TelLength] = {4,2,7}; int answer[TelLength] = {0,0,0}; cout << "427" << "对应的所有英文是:\n"; while(true) { for(int i = 0; i < TelLength; i ++) cout << c[number[i]][answer[i]]; cout << "\n"; int k = TelLength - 1; while(k >=0) { if(answer[k] < total[number[k]] - 1) { answer[k] ++; break; } else { answer[k] = 0; k --; } } if( k < 0) break; } getchar(); return 0; } void RecursiveSearch(char c[10][10], int total[10], int* number, int* answer, int index, int n) { if(index == n) { for(int i = 0; i < n; i ++) cout << c[number[i]][answer[i]]; cout << "\n"; return; } for(answer[index] = 0; answer[index] < total[number[index]]; answer[index] ++) { RecursiveSearch(c, total, number, answer, index + 1, n); } }解法二:递归方法
#include<iostream> #include<stdio.h> using namespace std; #define TelLength 3 void RecursiveSearch(char c[10][10], int total[10], int* number, int* answer, int index, int n); int main() { char c[10][10]= { "", //0 "", //1 "ABC", //2 "DEF", //3 "GHI", //4 "JKL", //5 "MNO", //6 "PQRS", //7 "TUV", //8 "WXYZ" //9 }; int total[10] = {0,0,3,3,3,3,4,3,4}; int number[TelLength] = {4,2,7}; int answer[TelLength] = {0,0,0}; cout << "427" << "对应的所有英文是:\n"; RecursiveSearch(c, total, number, answer, 0, TelLength); getchar(); cout << "hello world!" << endl; return 0; } void RecursiveSearch(char c[10][10], int total[10], int* number, int* answer, int index, int n) { if(index == n) { for(int i = 0; i < n; i ++) cout << c[number[i]][answer[i]]; cout << "\n"; return; } for(answer[index] = 0; answer[index] < total[number[index]]; answer[index] ++) { RecursiveSearch(c, total, number, answer, index + 1, n); } }
标签:
原文地址:http://blog.csdn.net/hhh3h/article/details/43888655