【发布时间】:2011-10-01 20:46:59
【问题描述】:
如果 groupSize=3, n=6 将打印,我如何将此 for 循环更改为递归 123 124 125 126 134 135 136 145 146 156 234 235 236 245 246 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);
}
}
}
}
}
}
【问题讨论】:
-
1. n 不能小于零 groupSize 大于 0 且小于 n。 2.你的第二个for循环不会运行,因为i的第一个值为1,所以当j为1时,它将大于1-1,即0。
-
你能发布你到目前为止所尝试的吗?
-
@Walkerneo:对我来说似乎是合理使用递归。
-
@MarkByers,是的,我一开始还以为他在做别的事情
-
好的,所以您尝试使用数字 1 到 n 打印所有具有 groupSize 中位数的数字,以使百位中的数字小于十位中的数字小于个位数?
标签: java loops recursion for-loop