在 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 表示輸入號碼的位數。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP