代码之家  ›  专栏  ›  技术社区  ›  daydayup

递归algorihtm的这两种实现有什么区别?

  •  1
  • daydayup  · 技术社区  · 8 年前

    我正在处理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);
            }
        }
    };
    

    版本2(更快):

    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];
            }
        }
    };
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Arkadiusz Rosiak    8 年前

    版本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!看一看图片,充分了解: Fibonacci recursion tree

    代码中也存在相同的情况。即使之前已经计算过uniquePaths(m,n),也可以计算它。为了避免这种情况,在第二个版本中,您使用数组存储计算数据,并且当 res[m][n]!=0