未知层的嵌套循环如何通过递归实现?
How can the nested loops of unknown layers be implemented by recursion?
int m =10;
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="+i+",j="+j+",k="+k+",l="+l);
}
}
}
}
比如代码片段是一个四层嵌套循环,循环之间有数据依赖,嵌套层数不确定,如何通过递归实现(嵌套不确定)?
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]) {
continue outer;
}
}
b[depth] = i;
recurse(a, b, depth + 1);
}
}
调用示例:
recurse(new int[] {10, 9, 4, 7}, new int[4], 0);
int m =10;
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="+i+",j="+j+",k="+k+",l="+l);
}
}
}
}
比如代码片段是一个四层嵌套循环,循环之间有数据依赖,嵌套层数不确定,如何通过递归实现(嵌套不确定)?
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]) {
continue outer;
}
}
b[depth] = i;
recurse(a, b, depth + 1);
}
}
调用示例:
recurse(new int[] {10, 9, 4, 7}, new int[4], 0);