【发布时间】:2020-05-21 16:05:37
【问题描述】:
我被一个递归问题困住了。这是字母键盘问题(问题是从一个数字中打印所有可能的组合,其中数字与字母相关的方式与电话键盘上的相同)!我无法解决它的原因是我需要制作一个 String 函数,但我不知道如何让它工作!我已经发布了我为解决这个问题而制作的 2 个函数,但它们给出了错误的答案。
输入:23
预期输出:ad ae af bd be bf cd ce cf
我得到的输出:cf
final static char[][] codes = { {' ',' ',' '}, {' ',' ',' '}, {'a','b','c'}, {'d','e','f'},
{'g','h','i'}, {'j','k','l'}, {'m','n','o'},
{'p','q','r','s'}, {'t','u','v'}, {'w','x','y','z'} };
//java
static char c[];
public static void printKeyWords(int num[] , int current , int n ) {
int i;
if (current == n) {
return;
}
for (i = 0; i < codes[num[current]].length; i++) {
c[current] = codes[num[current]][i];
printKeyWords(num , current +1 , n);
if(num[current] == 0 || num[current] == 1)
return;
}
}
// Return a string array that contains all the possible strings
public static String[] keypad(int input){
String s= Integer.toString(input);
int num [] = new int[s.length()];
for (int i = 0; i < s.length(); i++){
num[i] = s.charAt(i) - '0';
}
c = new char[num.length + 1];
printKeyWords(num , 0 ,num.length);
String str = new String(c);
String strArray[] = str. split(" ");
return strArray;
}
【问题讨论】:
-
请告诉我你想要的输入和输出
-
能否在您的文字中描述“字母键盘问题”?
-
当你设置最后一个字符时(当 current 等于 n 减一时),你需要把它记录为一个解。您只在递归结束后查看解决方案,因此您只会看到最后一个解决方案。此外,没有理由拆分字符串。另外,为什么
c的大小为num.length + 1?+ 1是干什么用的?此外,您需要一个List<String>来附加解决方案。你事先不知道会有多少解决方案。 (理论上你可以计算出这个数字;实际上,只需使用List并添加它。) -
@DavidConrad 对不起,我还是个新手。所以我不知道如何使用
List<String>。因此我遇到了一个很大的问题,因为这是我从互联网上找到的旧代码。我尽力挽救每一点,所以有一些我自己不知道的部分,但我把它们留在那里希望它们能工作 -
哦!我很抱歉 !我马上就做@ggorlen
标签: java recursion combinations letter keypad