网站上有一些类似的问题,这些问题对我有一些帮助,但我无法完全确定这个问题,所以我希望这不是重复的。
这是一项家庭作业,其中您有一组字符 [A,B,C],并且必须使用递归来获取所有排列(有重复)。我的代码是这样做的:
char[] c = {'A', 'B' , 'C'};
public void printAll(char[] c, int n, int k) {
if (k == n) {
System.out.print(c);
return;
}
else {
for (int j = 0; j<n; j++) {
for (int m = 0; m<n; m++) {
System.out.print(c[k]);
System.out.print(c[j]);
System.out.print(c[m] + "\r\n");
}
}
}
printAll(c, n, k+1);
}
然而,参数 n 应该定义输出的长度,所以虽然这个函数打印出长度为 3 的所有排列,但它不能打印长度为 2 的排列。我已经尝试了我能想到的一切,并仔细研究了 Google 搜索结果,我对自己无法解决看似相当简单的问题感到恼火。
如果我理解正确的话,你会得到一组字符c
和所需的长度n
.
从技术上讲,不存在重复排列这样的事情。我假设你想要所有长度的字符串n
信件来自c
.
你可以这样做:
to generate all strings of length N with letters from C
-generate all strings of length N with letters from C
that start with the empty string.
to generate all strings of length N with letters from C
that start with a string S
-if the length of S is N
-print S
-else for each c in C
-generate all strings of length N with letters from C that start with S+c
In code:
printAll(char[] c, int n, String start){
if(start.length >= n){
System.out.println(start)
}else{
for(char x in c){ // not a valid syntax in Java
printAll(c, n, start+x);
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)