您好,我是编程新手,并注册了此论坛:)
因此,我创建了一个带有嵌套 for 循环的小程序,该程序打印出 5 个数字的所有组合,这些数字的值可以从 0 到 5。使用嵌套 for 循环,效果很好。但没有更清洁的解决方案吗?我尝试调用 for 循环本身,但我的大脑没有得到解决方案..:(
//my ugly solution
int store1, store2, store3, store4, store5;
for (int count = 0; count <= 5; count++) {
store1 = count;
for (int count2 = 0; count2 <= 5; count2++) {
store2 = count2;
for (int count3 = 0; count3 <= 5; count3++) {
store3 = count3;
for (int count4 = 0; count4 <= 5; count4++) {
store4 = count4;
System.out
.println(store1 + " " + store2 + " " + store4);
}
//I'm trying around with something like this
void method1() {
for (int count = 0; count <= 5; count++) {
list.get(0).value = count;
count++;
method2();
}
}
void method2() {
for (int count = 0; count <= 5; count++) {
list.get(1).value = count;
count++;
method1();
}
}
最佳答案
通常,当人们尝试使用递归或函数时,使用循环会更简单或更快。但是,在这种情况下,递归与循环结合使用是更简单的选项。
public static void method(List<Integer> list, int n, int m) {
if (n < 0) {
process(list);
} else {
for(int i = 0; i < m; i++) {
list.set(n, i);
method(list, n-1, m);
}
}
}
关于java - 嵌套 For 循环动态深度 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13865235/