【问题标题】:How to analyze time complextity for recursiion如何分析递归的时间复杂度
【发布时间】:2017-08-19 18:03:04
【问题描述】:

我使用递归完成了一个 leetcode 问题329:Given an integer matrix, find the length of the longest increasing path.,但我不确定它的时间复杂度。

为了时间复杂度,先在外面有for循环。因此,它是 T(m, n) = O(m*n) 对于两个循环。在循环内部,有一个递归调用findPath。就像

  T(m,n) = T(m-1, n)+T(m+1, n)+T(m, n-1)+T(m, n+1)

我完全迷失了这个。谢谢你能帮我解释一下。

以下是我的代码:

int longestIncreasingPath(vector<vector<int>>& matrix) {
    if (matrix.size() == 0 || matrix[0].size() == 0) return 0;
    vector<vector<int>> cached(matrix.size(), vector<int>(matrix[0].size(), 0));
    int maxVal =0;
    for(int i=0; i<matrix.size(); i++){
        for(int j=0; j<matrix[0].size();j++){
            int length = findPath(matrix, i, j , cached, INT_MAX);
            maxVal=max(length, maxVal);
        }
    }
    return maxVal;
}

int findPath(vector<vector<int>>& matrix, int i, int j, 
             vector<vector<int>>& cached, int lastValue){
    if(i<0 || j<0 || i>=matrix.size() || j>=matrix[0].size() || matrix[i][j]>=lastValue){
        return 0;
    }
    if(cached[i][j]==0) {
       int current = matrix[i][j];
       int temp = 0;
       temp= max(temp, findPath(matrix, i-1, j, cached, current));
       temp= max(temp, findPath(matrix, i+1, j, cached, current));
       temp= max(temp, findPath(matrix, i, j-1, cached, current));
       temp= max(temp, findPath(matrix, i, j+1, cached, current));
       cached[i][j] = temp+1;
   }
   return cached[i][j];
} 

【问题讨论】:

    标签: recursion time-complexity big-o


    【解决方案1】:

    在每次调用findPath 之后,cached[i][j] 的内容将始终大于 1。因此对位置 (i, j) 的后续调用将不会导致对其周围位置的递归调用.然后我们可以推断出每个位置(i, j) 被称为最多 4 次,因为它只能通过调用水平或垂直相邻的位置来访问,只有第一个位置会导致进一步递归调用。我们还假设matrix[i][j] &gt;= lastValue从不满足的最坏情况。因此上限为O(mn),其中m, nmatrix 的维度。

    【讨论】:

      猜你喜欢
      • 2020-09-19
      • 1970-01-01
      • 2017-05-29
      • 2022-06-22
      • 2022-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多