gpt4 book ai didi

java从for循环到递归寻找组合

转载 作者:行者123 更新时间:2023-12-01 15:43:21 25 4
gpt4 key购买 nike

如果 if groupSize=3, n=6 将打印,我如何将此 for 循环更改为递归123124125126134135136145146156234235236245246第345章第346章第356章456

public static void printCombinations(int groupSize, int n){

if (groupSize <=n && groupSize>0 && n>0){

for (int i=1; i<=n; i++){
for (int j=1; j<=i-1; j++){
for (int k=1; k<=j-1; k++){
int first = k;
int second = j;
int third = i;
if (i!=j && i!=k && j!=k){
System.out.println(first +" " + second +" "+ third);
}
}
}
}
}
}

最佳答案

边缘可能会比较粗糙;我刚刚学习 Java。

class comboMaker {
public static void main(String args[]){
String[] test1 = startCombo(3,6);
prnt(test1);
}
private static String[] startCombo(int len,int digits){
return combos(len,digits,"",0);
}
private static String[] combos(int len,int digits,String cur,int lastdig){
if (len>digits){
return null;
}
if (cur.length()==len){
return new String[]{cur};
}
String tmp = cur;
String[] rtn = {};
for(int i = lastdig+1;i<=digits;i++){
tmp=cur+Integer.toString(i);
rtn=concat(rtn,combos(len,digits,tmp,i));
}
return rtn;

}
private static String[] concat(String[] A, String[] B) {
String[] C= new String[A.length+B.length];
System.arraycopy(A, 0, C, 0, A.length);
System.arraycopy(B, 0, C, A.length, B.length);
return C;
}

private static void prnt(String[] str){
if(str==null){
System.out.println("Invalid string array");
return;
}
for(int i =0;i<str.length;i++ ){
System.out.println(str[i]);
}
}
}

我包含了一种连接数组的方法,我在这里找到了:How can I concatenate two arrays in Java?

还有一种打印组合生成器生成的字符串数组的方法。

关于java从for循环到递归寻找组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7622874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com