【发布时间】: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