如下代码是 6 层 for 循环。
ublic void forSix() {
String preFix = "101";
String postFix = "11";
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
for (int l = 0; l < 2; l++) {
for (int m = 0; m < 2; m++) {
for (int n = 0; n < 2; n++) {
// operation
System.out.println(preFix+i+j+k+l+m+n+postFix);
}
}
}
}
}
}
}
如果碰到更为复杂的应用场景,可能存在更深层次的嵌套 for 循环,如 10、13层等,乃至于更多。
如何简化 for 循环的层次?可以使用递归解决问题。
ublic static final String PRE_FIX = "101";
public static final String POST_FIX = "11";
public final StringBuilder sb = new StringBuilder();
public void simpleFor(int level) {
if (level > 6) {
return;
}
for (int i = 0; i < 2; i++) {
sb.Append(i);
if (level == 6) {
System.out.println(PRE_FIX + sb + POST_FIX);
}
simpleFor(level + 1);
sb.deleteCharAt(sb.length() - 1);
}
}
以上代码每一层 for 循环的数组都是相同,如果每一层需要循环的数组不同该怎么办?
可以使用 Map<Integer, Integer[]> 保存相关数组,索引为 level
.
ublic static final String PRE_FIX = "101";
public static final String POST_FIX = "11";
public final StringBuilder sb = new StringBuilder();
public final Map<Integer, Integer[]> integerMap = new HashMap() {{
put(1, new Integer[]{0,1,2,3,4,5,6,7,8,9});
put(2, new Integer[]{0,1,2,3,4,5,6,7,8,9});
put(3, new Integer[]{0,1,2,3,4,5,6,7,8,9});
put(4, new Integer[]{0,1,2,3,4,5,6,7,8,9});
put(5, new Integer[]{0,1,2,3,4,5,6,7,8,9});
put(6, new Integer[]{0,1,2,3,4,5,6,7,8,9});
}};
public void simpleForOptimize(int level) {
if (level == 7) {
return;
}
Integer[] integers = integerMap.get(level);
for (Integer integer : integers) {
sb.append(integer);
if (level == 6) {
System.out.println(PRE_FIX + sb + POST_FIX);
}
simpleForOptimize(level + 1);
sb.deleteCharAt(sb.length() - 1);
}
}