标签:
原始问题如下:手机上面的数字键均对应了几个字符,譬如2对应了a,b,c。问题是当输入一段数字后,求出所有可能的字符组合
第一种方法:假设电话号码是n个数字,那么就n个for循环。
这方法果断不好
第二个方法:
#include <iostream> #include <string> using namespace std; char c[10][10] = { "", "", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ", }; int total[10] = {0, 0, 3, 3, 3, 3, 3, 4, 3, 4}; int tel_length; int number[10], answer[10]; int main(int argc, const char * argv[]) { cin >> tel_length; for(int i = 0; i < tel_length; ++i) cin >> number[i]; memset(answer, 0, sizeof(answer)); while(true) { for (int i = 0; i < tel_length; i++) { printf("%c", c[number[i]][answer[i]]); } puts("\n"); int k = tel_length-1; while(k >= 0) { if(answer[k] < total[number[k]] - 1) { answer[k]++; break; } else { answer[k] = 0; k--; } } if(k < 0) break; } return 0; }
第三个方法:回溯法:
#include <iostream> #include <string> using namespace std; char c[10][10] = { "", "", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ", }; int total[10] = {0, 0, 3, 3, 3, 3, 3, 4, 3, 4}; int tel_length; int number[10], answer[10]; void RecursiveSearch(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 << endl; return ; } else { for (answer[index] = 0; answer[index] < total[number[index]]; answer[index]++) { RecursiveSearch(number, answer, index+1, n); } } } int main(int argc, const char * argv[]) { cin >> tel_length; for(int i = 0; i < tel_length; ++i) cin >> number[i]; memset(answer, sizeof(answer), 0); RecursiveSearch(number, answer, 0, tel_length); return 0; }
标签:
原文地址:http://blog.csdn.net/u010470972/article/details/45166613