The following example:
public class Test4 {public
static void Main (string[] args) {
int m = ten;
int n = 9;
int p = 4;
int q = 7;
for (int i=0;i<m;i++) {
int a = i;
for (int j=0;j<n;j++) {
int b = j;
if (b==a) {
continue;
}
for (int k=0;k<p;k++) {
int c = k;
if (c==b | | c==a) {
continue;
}
for (int l=0;l<q;l++) {
int d = l;
if (d==c | | d==b | | d==a) {
continue;
}
System.out.println ("[" +i+ "," +j+ "," +k+ "," +l+ "]");}}}}}
If the number of nested loops is specified dynamically, it cannot be achieved by the way above, which can only work if the number of nested loops is determined.
How to break, using recursion can skillfully solve the above scenario, the code is as follows:
Import Java.util.Arrays;
public class test5{public
static void Main (string[] args) {
recurse (new int[] {5, 2, 4}, new Int[3], 0);
} Public
static void Recurse (int[] A, int[] b, int depth) {
if (depth = = a.length) {
System.out.println (Arrays). ToString (b));
return;
}
Outer: for
(int i = 0; i < a[depth], i++) {for
(int j = 0; j < depth; J + +) {
if (i = = B[j]) {
C Ontinue outer;
}
}
B[depth] = i;
Recurse (A, B, depth + 1);}}}
As you can see by comparison, the code that is implemented recursively is very concise and elegant, but it is also very inefficient, especially when the number of loops and the depth of nesting are large.