leetcode刷题,总结,记录,备忘 329

leetcode329,

Longest Increasing Path in a Matrix

 

Given an integer matrix, find the length of the longest increasing path.

From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).

Example 1:

nums = [
  [9,9,4],
  [6,6,8],
  [2,1,1]
]

Return 4
The longest increasing path is [1, 2, 6, 9].

Example 2:

nums = [
  [3,4,5],
  [3,2,6],
  [2,2,1]
]

Return 4
The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

第一时间想到肯定是深度优先,从每个位置开始,递归每一种可能的路线,在遇到不大于之前的数的时候和碰到之前遇到过的点的时候返回。第一次写的结果是正确的,但是使用的内存太多了,原因是我把每种情况的数组集合都缓存了下来,其实并不需要,之需要知道最大的数组的维数就行了。使用一个数组保存以每个点为起点的最大路径长,以免反复计算,减少时间复杂度。具体见代码,还是比较好理解的。

class Solution {
public:
    int function(vector<vector<int> > & matrix, int i, int j, int rows, int cols, vector<vector<int> > & dp)
    {
        if (dp[i][j] != -1)
        {
            return dp[i][j];
        }
        
        int left = 0;
        int right = 0;
        int up = 0;
        int down = 0;
        
        //left
        if (j != 0 && matrix[i][j - 1] > matrix[i][j])
        {
            left = function(matrix, i, j - 1, rows, cols, dp);
        }
        
        //right
        if (j != cols - 1 && matrix[i][j + 1] > matrix[i][j])
        {
            right = function(matrix, i, j + 1, rows, cols, dp);
        }
        
        //up
        if (i != 0 && matrix[i - 1][j] > matrix[i][j])
        {
            up = function(matrix, i - 1, j, rows, cols, dp);
        }
        
        //down
        if (i != rows - 1 && matrix[i + 1][j] > matrix[i][j])
        {
            down = function(matrix, i + 1, j, rows, cols, dp);
        }
        
        dp[i][j] = max(max(left, right), max(up, down)) + 1;
        
        return dp[i][j];
    }
    
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        if (matrix.size() == 0)
        {
            return 0;
        }
        
        int rows = matrix.size();
        int cols = matrix[0].size();
        
        vector<vector<int> > dp(rows, vector<int>(cols, -1));
        int max_result = 0;
        for (int i = 0; i < rows; ++i)
        {
            for (int j = 0; j < cols; ++j)
            {
                max_result = max(max_result, function(matrix, i, j, rows, cols, dp));
            }
        }
        
        return max_result;
        
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值