簡體   English   中英

為什么遞歸轉到 else 塊而不是 if?

[英]Why does the recursion goes to else block instead of if?

class myclass {
   static int fun(int a[],int n){
      int x;

      if(n == 1){
        return a[0];
      }
      else{
           x = fun(a, n-1);

          if(x > a[n-1])
              return x;
          else
             return a[n-1];
      }
}
 public static void main(String[] args){
     int arr[] = {12, 10, 30, 50, 100};
     System.out.println(fun(arr, 5));}
}

為什么 output 是 100 而不是 12。我不明白為什么當 n 的值為 1 時最后一次遞歸調用,它會阻塞而不是 if。

這是因為您正在尋找數組中的最大值 if(x > a[n-1])更改為if(x < a[n-1])將使您的程序為給定的輸入返回 10。

這是因為您在最后返回到相同 function 的先前實例,因此您的方法調用和返回看起來像這樣(每個級別縮進是一個 function 調用及其返回)。 如果您知道如何使用調試器,請單步執行您的代碼並在 go 中查看並繪制此圖,這將幫助您能夠在腦海中可視化遞歸調用和每次返回的值。

fun(a[],5) 
 |   fun(a[],4) 
 |   |   fun(a[],3)
 |   |   |  fun(a[],2)
 |   |   |   |  fun(a[],1)
 |   |   |   |  return 12
 |   |   |   return 12
 |   |   return 30
 |   return 50
 return 100
  1. N=1, x= 12, 12 > a[0] (12) ---> 返回 a[1-1] = 12
  2. N=2。 x=12, 12 > a[1] (10) --> 返回 x = 12;
  3. N=3。 x=12, 12> a[2] (30) --> 返回 a[3-1] = 30
  4. N =4 x =30, 30 > a[3] (50) --> 返回 a[4-1] = 50
  5. N=5 x =50, 50 > a[4] (50) ---> 返回 a[5-1] = 100

這里詳細說明為什么結果是100

public class myclass {
 static int fun(int a[],int n)
{
 int x;
 if(n == 1)
{
 return a[0];   // Step (2) --> return x = 12, now again n = 5 then continue on line        
}
 else
{
 x = fun(a, n-1); // Step (1) --> this line is same as x = fun(a, 1)
 if(x > a[n-1])     // Step (3) --> at this point n = 5 again and x = 12 while a[4] = 100 which is not less than x, statement 12 > 100 is false, move on to else block
 return x;
 else
 return a[n-1];  // Step (4) --> return a[4] which is 100 as see above
}
}
 public static void main(String[] args)
{
 int arr[] = {12, 10, 30, 50, 100};
 System.out.println(fun(arr, arr.length));}
}

希望您能理解遞歸示例中缺少的內容!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM