【问题标题】:How to make a recursive method?如何制作递归方法?
【发布时间】:2018-05-29 03:14:12
【问题描述】:

我正在尝试制作这种递归方法。

public int addWithFactors(int[] a, int n) {
    int sum = 0;
    for (int i = 0; i < n; i++) {
        sum = sum + (i + 1) * a[i];
    }
    return sum;
}

我试图用 if 语句代替 for 循环:

if (n == 0) {...}

但我不知道递归等价物是什么

【问题讨论】:

  • 要使用递归方法,您必须在其中调用 addWithFactors。
  • public static int addWithFactors(int[] a, int i) { return i &lt; a.length ? a[i] * (i + 1) + addWithFactors(a, i + 1) : 0; }

标签: java recursion


【解决方案1】:

您可以将此代码视为其递归等效项。在您的原始代码中,您将a 设置为给定数组,将n 设置为最大项,最多为a.length - 1,将i 设置为当前项。您的程序实际上是一个求和程序。

递归帮助器版本如下图所示,它还可以处理i越界等异常情况:

public int addWithFactorsRecursive(int[] a, int i, int n) {
    if (i < 0) // Exceptional case where 
        return -1;
    else if (i == n - 1) // End recursion here 
        return (i + 1) * a[i];
    else if (i < n - 1) // Return the term, and consider further terms
        return (i + 1) * a[i] + addWithFactorsRecursive(a, i + 1, n);
    return 0;
}

我将向您展示的输出将采用数组输入a,并将addWithFactors(a, 0) 循环到addWithFactors(a,a.length)

这是我使用的一个输入,{1,4,9,16} 和我得到的输出,左侧是您当前的迭代版本,右侧是递归版本:

0 1 // n == 0 
1 1 // n == 1 
9 9 // n == 2 
36 36 // n == 3 

{2,4,8,16,32,64} 也一样,我得到了

0 2
2 2
10 10
34 34
98 98
258 258

【讨论】:

    【解决方案2】:

    你可以这样定义你的函数:

    public int addWithFactors(int[] a, int n) {
         if (n == 1)
                return a[n - 1];
         return (n) * a[n - 1] + addWithFactors(a, n - 1);
    }
    

    你应该这样称呼它:

        addWithFactors(new int[] {1, 1, 2} ,3)
    

    它返回 9。

    【讨论】:

      【解决方案3】:
      private int addWithFactorsInternal(int[] a, int n, int i) {
         if (i == n) {
            return 0; //base case
         }
         return addWithFactors(a, n, i + 1) + (i + 1) * a[i];
      }
      

      addWithFactors(a, n, i + 1) 进行递增i 的递归调用。基本情况是 i 到达 n 时返回 0。

      对于其他人,您将(i + 1) * a[i] 添加到递归调用并返回。

      如果您的顶级方法是您提到的签名,则可以将上述方法称为

      public int addWithFactors(int[] a, int n) {
           return addWithFactorsInternal(a, n, 0);
      }
      

      注意:我没有假设 n 等于 a.length

      例子:

      a = {1,4 5}n = 3(从上到下读取LHS,从下到上读取RHS)

      [返回 24]

      addWithFactorsInternal(a, 3, 0) - 23 + (0 + 1) * 1 = 24
      addWithFactorsInternal(a, 3, 1) - 15 + (1 + 1) * 4 = 23
      addWithFactorsInternal(a, 3, 2) - 0 + (2 + 1) * 5 = 15
      addWithFactorsInternal(a, 3, 3) - returns 0 (base case)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-02
        相关资源
        最近更新 更多