在 C/C++ 中,如何获取所有可以用来拨打电话号码的字符串组合?
针对给定的号码,使用以下规范,显示或打印所有可以用来拨打该号码的字符串组合。
在给定的电话中,我们可以拨打:
2 表示 A 或 B 或 C,
3 表示 D 或 E 或 F,
……
8 表示 T 或 U 或 V,
9 表示 W 或 X 或 Y 或 Z,
1 仅表示 1,
0 表示 0。
例如,如果给定的电话号码是 89,程序应该打印:
TW,TX,TY,TZ,UW,UX,UY,UZ,VW,VX,VY,VZ
#include <stdio.h> #include <string.h> // TableHash[i] stores all characters that correspond to digit i in phone const char TableHash[10][5] = {"", "", "WXYZ", "TUV", "PQRS", "MNO", "GHI", "GHI", "DEF", "ABC"}; // A recursive function to display or print all possible words that can be obtained by implementing input number1[] of size n1. The output words are one by one stored in output1[] void UtilWordsPrint(int number1[], int curr_digit1, char output1[], int n1) { // In the Base case, if current output word is prepared int i; if (curr_digit1 == n1) { printf("%s ", output1); return ; } // We try all 3 possible characters for current digit in number1[] // and recur for remaining digits for (i=0; i<strlen(TableHash[number1[curr_digit1]]); i++) { output1[curr_digit1] = TableHash[number1[curr_digit1]][i]; UtilWordsPrint(number1, curr_digit1+1, output1, n1); if (number1[curr_digit1] == 0 || number1[curr_digit1] == 1) return; } } // A wrapper over UtilWordsPrint(). It is able to create an output1 array and calls UtilWordsPrint() void printWords(int number1[], int n1) { char result1[n1+1]; result1[n1] ='\0'; UtilWordsPrint(number1, 0, result1, n1); } //Driver program int main(void) { int number1[] = {2, 3, 4}; int n1 = sizeof(number1)/sizeof(number1[0]); printWords(number1, n1); return 0; }
输出
WTP WTQ WTR WTS WUP WUQ WUR WUS WVP WVQ WVR WVS XTP XTQ XTR XTS XUP XUQ XUR XUS XVP XVQ XVR XVS YTP YTQ YTR YTS YUP YUQ YUR YUS YVP YVQ YVR YVS ZTP ZTQ ZTR ZTS ZUP ZUQ ZUR ZUS ZVP ZVQ ZVR ZVS
时间复杂度:上述代码的时间复杂度为 O(4n),其中 n 表示输入号码的位数。
广告