gpt4 book ai didi

java - 无法理解这个递归

转载 作者:行者123 更新时间:2023-12-02 05:18:33 24 4
gpt4 key购买 nike

输入为{4,7,3,6,7},输出为:

[81]
[40, 41]
[21, 19, 22]
[11, 10, 9, 13]
[4, 7, 3, 6, 7]

我为此使用的递归程序如下,我在其中添加了一些打印语句来理解递归:

import java.util.Arrays;

public class triangle_array {
public static void print(int a[])
{
if(a.length==0)
return;
int n=a.length;
int newa[]=new int[n-1];
for(int i=0;i<n-1;i++)
{
newa[i]=a[i]+a[i+1];
}
System.out.println("here1") ;
print(newa);
System.out.println("here2") ;
if(newa.length!=0)
System.out.println(Arrays.toString(newa));
}

public static void main(String args[])
{
int a[]={4,7,3,6,7};
print(a);
System.out.println(Arrays.toString(a));
}

}

我得到的输出为:

here1
here1
here1
here1
here1
here2
here2
[81]
here2
[40, 41]
here2
[21, 19, 22]
here2
[11, 10, 9, 13]
[4, 7, 3, 6, 7]

我无法完全理解这个递归,从上面的 here 语句中,我了解到 print 方法首先被递归调用,当条件失败时,它返回到 print 之外并转到该行并打印“here2”2 次,它验证 newa 的长度是否为零,直到这一点我明白了,但是在接下来的迭代中,对于 println 语句,newa 的长度如何增加以及以下条件如何变为真?

最佳答案

一般情况下,如果递归方法中有打印,则递归调用之前的所有打印都会按照递归深度递增的顺序打印,而递归调用之后的所有打印都会按照递归深度递增的顺序打印。颠倒顺序。

public static void demoRecursion( int n, int depth ) {

if ( n <= 0 ) {
return;
}

System.out.println( "Before recursive call, depth " + depth );

demoRecursion( n - 1, depth + 1 );

System.out.println( "After recursive call, depth " + depth );

}

如果您使用 demoRecursion( 3, 1 ) 调用此方法,您将得到:

Before recursive call, depth 1
Before recursive call, depth 2
Before recursive call, depth 3
After recursive call, depth 3
After recursive call, depth 2
After recursive call, depth 1

所以,a 的大小并没有增加。很简单,在深度 1 处,您有一个 5 项数组,在深度 2 处,您有一个 4 项数组,在深度 3 处,您有 3 项数组,依此类推。

因此,由于我上面演示的反向打印效果,每个深度的数组都打印在较深层的数组之后,该数组较短。

如果您在递归调用之前打印了数组,则打印结果将按降序排列。

关于java - 无法理解这个递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26701310/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com