递归解释

Bar*_*t g 2 java recursion

今天在Java课程中,教授提出了这个例子,但是我真的不能很好地理解如何通过这种方法来获得结果的过程= 4.可以任何一个身体请尽可能清楚地说明一些线条怎么这个方法解决了?谢谢好,所以这是方法:

public static int mystery(int[] values, int start, int value)
{
    if(start == values.length) {
        return value;
    }
    else
        return Math.max(value, mystery(values, start+1, values[start]));
}
Run Code Online (Sandbox Code Playgroud)

Luc*_*ore 8

结果不是4,而是数组中的最大值.

它是这样的:

values 是元素的数组.

start 是当前的指数.

value 是当前的最大值.

如果当前索引超过了数组的长度,则返回当前最大值.这是第一行代码和暂停条件.

否则,返回当前索引之前当前最大值和最大值之间的最大值.这将以递归方式最终返回数组中的最大值.

您最初使用start = 0和调用此函数value = 0.

假设values = [2,5,1].

mystery ( [2,5,1], 0 , 0 ) ->
  start (0) != values.length (3) ->
  return max (0, mystery( [2,5,1], 1, 2 ) ->
      mystery ( [2,5,1], 1, 2 ) ->
        start (1) != values.length ->
        return max (2, mystery( [2,5,1], 2, 5 ) ->
            mystery ([2,5,1], 2, 5) ->
            start(2) != values.length ->
                return max(5, mystery( [2,5,1], 3, 2) ->
                   start(3) == values.length ->
                   return value (1)
                -> return max(5,1)
            -> return 5
         -> return max(2,5)
       -> return 5
   -> return max(0,5)
-> return 5
Run Code Online (Sandbox Code Playgroud)