【问题标题】:Is this method a case of recursion or an Iteration?这种方法是递归还是迭代?
【发布时间】:2014-03-24 08:13:41
【问题描述】:

我一直在努力理解递归,它适用于一些例子,比如斐波那契,也适用于下面的加法序列..

int AdditiveSequence(int n, int t0, int t1){
    if(n == 0) return t0;
    if(n == 1) return t1;
    return AdditiveSequence(n - 1, t1, t0 + t1);
}

我考虑了如何应用并尝试了这个:

static final double PERCENT = 0.005;

double Depreciation(int month, double currentValue){
    if(month == 0)return currentValue;
    return Depreciation(month - 1, currentValue -= currentValue * PERCENT);
}

但这似乎不是递归,更像是迭代,因为当我在 Eclipse 调试屏幕中查看时,它在月份 == 0 时退出,而迭代的 currentValue 被正确返回。

在 Factorial(n) 方法的情况下:

int Factorial(f){
    if(f == 1){
      return 1;
    }else{
      return f * Factorial(f - 1);
    }
}

它似乎推迟计算直到达到基本情况,然后返回堆栈直到达到结果......

谁能帮我确定我用上述折旧方法做了什么,以及它实际上是递归还是迭代。

【问题讨论】:

  • 我认为这是递归,因为函数引用自身,所以它就像一个链,直到条件成功并且所有链都返回。
  • 正如@solvator所说,这绝对是一个递归,因为它调用自己来计算返回值。
  • 注意,你应该使用currentValue - (currentValue * PERCENT),因为在当前递归中修改currentValue是没有意义的。
  • 是源码层的递归。现在,JVM 可以做哪些优化以使递归“更快”?这可以解释调试输出。

标签: java recursion iteration


【解决方案1】:

这实际上称为尾递归,这意味着当您到达递归结束时,您就有了结果。这种类型的递归很容易转换为迭代代码,并且通常由编译器完成

static final double PERCENT = 0.005;

double Depreciation(int month, double currentValue){
    if(month == 0)return currentValue;
    return Depreciation(month - 1, currentValue -= currentValue * PERCENT);
}

在您的情况下,当前值一直在累积,这就是它适合尾递归配置文件的原因。

【讨论】:

    【解决方案2】:

    我认为 AdditiveSequence 也必须称为尾递归,因为它在完成时也退出 - 即 (n == 1)return t1;因为满足计算...

    【讨论】:

    猜你喜欢
    • 2011-05-23
    • 2011-09-21
    • 2015-03-24
    • 2017-03-31
    • 2012-06-16
    • 2012-06-25
    • 2012-04-18
    相关资源
    最近更新 更多