【问题标题】:what is the difference of these two implementations of a recursion algorihtm?递归算法的这两种实现有什么区别?
【发布时间】:2016-06-27 04:39:46
【问题描述】:

我正在做一个 leetcode 问题。

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

How many possible unique paths are there?

所以我首先尝试了这个实现并得到了“超过运行时间”(我忘记了确切的术语,但这意味着实现很慢)。所以我将其更改为版本 2,它使用数组来保存结果。老实说,我不知道递归在内部是如何工作的,以及为什么这两种实现具有不同的效率。

版本 1(慢):

class Solution {
   // int res[101][101]={{0}};
public:
    int uniquePaths(int m, int n) {
        if (m==1 || n==1) return 1;
        else{ 
            return uniquePaths(m-1,n) + uniquePaths(m,n-1);
        }
    }
};

version2(更快):

class Solution {
    int res[101][101]={{0}};
public:
    int uniquePaths(int m, int n) {
        if (m==1 || n==1) return 1;
        else{ 
            if (res[m-1][n]==0) res[m-1][n] = uniquePaths(m-1,n);
            if (res[m][n-1]==0) res[m][n-1] = uniquePaths(m,n-1);
            return res[m-1][n] + res[m][n-1];
        }
    }
};

【问题讨论】:

标签: recursion


【解决方案1】:

版本 1 速度较慢,因为您一次又一次地计算相同的数据。我会尝试在不同的问题上解释这一点,但我想你知道斐波那契数。您可以通过以下递归算法计算任何斐波那契数:

fib(n):
if n == 0 then return 0
if n == 1 then return 1
return fib(n-1) + fib(n-1)

但实际上你在计算什么?如果你想找到fib(5)你需要计算fib(4)和fib(3),然后计算fib(4)你需要再次计算fib(3)!看一下图片就完全明白了:

您的代码中也有同样的情况。即使您之前计算过 uniquePaths(m,n) ,您也可以计算它。为避免这种情况,在您的第二个版本中,您使用数组来存储计算数据,并且在 res[m][n]!=0 时不必再次计算它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 2019-03-31
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多