繁体   English   中英

如何制作一个递归方法?

[英]How to make a recursive method?

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

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) {...}

但我不知道递归等效项是什么

您可以这样定义函数:

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。

您可以将此代码视为其递归等效代码。 在原始代码中,将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
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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM