【问题标题】:Translating recursive method into an iterative method将递归方法转换为迭代方法
【发布时间】:2021-08-09 05:39:11
【问题描述】:

我想使用 while 或 for 循环将此递归方法更改为迭代方法,但遇到了麻烦。这是我要翻译的递归方法:

public static int recursiveNum (int n)
   {
      if(n<=2)
      {  
          return 1;     
      }
      else
      {       
         return recursiveNum(n-1)+recursiveNum(n-2);
      }
   }

到目前为止我所做的尝试:

public static int iterativeNum (int n) { 
      while (i<n) {
         i++;
         if (n<=2) {
            return 1; 
            }
        
         else {
            return n = (n-1) + (n-2);
            }
         }
         return n;
      }

【问题讨论】:

  • public static int iterativeNum (int n) { while (i
  • (n-1) + (n-2) 对索引求和,而不是求和。您需要几个变量来跟踪以前的总和。
  • 并且循环中间不应该有return。您不能只是将递归代码转储到一个循环中,然后希望它能够正常工作。
  • 如果我创建另一个变量,当 n 大于 3 时,我是否还需要更多?我应该使用数组吗?
  • 为什么要使用while循环?斐波那契数列最好用函数的递归性来描述。

标签: java recursion iteration


【解决方案1】:

这是斐波那契数,您可以通过循环和使用 3 个变量来完成

public static int f(int n) {
    if (n<=2) {
      return 1;
    } else {
      int n1=0;
      int n2=1;
      int n3=0;
      for (int i=2;i<=n;i++){
          
          n3=n1+n2;
          n1=n2;
          n2=n3;
        }
      return n3;
    }
  }



public class Main
{
    public static void main(String[] args) {
            int result = f(10);
            System.out.println(result);
    }
}

输出

55

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-08
    • 1970-01-01
    • 2017-08-01
    • 2015-05-09
    • 2016-06-29
    • 2015-07-06
    • 1970-01-01
    相关资源
    最近更新 更多