Lintcode 389 Longest Increasing Continuous subsequence II

Give you an integer matrix (with row size n, column size m),find the longest increasing continuous subsequence in this matrix. (The definition of the longest increasing continuous subsequence here can start at any row or column and go up/down/right/left any direction)


通过最小堆的动态规划迭代依次更新各个二维节点的最长递增序列的值。


这道题我开始用的是dfs,从首元素开始递增遍历更新二维节点的最长递增序列的值,但是最坏复杂度达到了n^4(逆序的时候)。

但是经过仔细一想,发现根本不需要进行深度遍历,只需要从小到大依次对节点的四个方向的值进行更新节点的最长递增序列,并更新最长值,直至便利完整个堆。时间复杂度为堆的构建时间 2(n^2)logn + 出堆时间4*2(n^2)logn,故总的时间复杂度为10(n^2)logn。



struct Point{
    int x;
    int y;
    int v;
    Point(int a,int b,int c):x(a),y(b),v(c){}
};

struct ValCmp{
    bool operator() (const Point &A,const Point &B){
        return A.v > B.v;
    }
};

class Solution {
public:
    /**
     * @param A an integer matrix
     * @return  an integer
     */
    int longestIncreasingContinuousSubsequenceII(vector<vector<int>>& A) {
        // Write your code here
        int m = A.size();
        if(!m) return 0;
        int n = A[0].size();
        if(!n) return 0;
        int res[m][n],maxres=1;
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                res[i][j] = 1;
            }
        }
        priority_queue<Point,vector<Point,allocator<Point>>,ValCmp> pq;
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                pq.push({i,j,A[i][j]});
            }
        }
        Point tmpp(0,0,0);
        int i,j,v;
        while(!pq.empty()){
            tmpp = pq.top();
            pq.pop();
            i = tmpp.x;j = tmpp.y;v = tmpp.v;
            if(i > 0 && A[i][j] < A[i-1][j] && res[i-1][j] < res[i][j] + 1){//up
                res[i-1][j] = res[i][j] + 1;
            }
            if(j > 0 && A[i][j] < A[i][j-1] && res[i][j-1] < res[i][j] + 1){//left
                res[i][j-1] = res[i][j] + 1;
            }
            if(i < m-1 && A[i][j] < A[i+1][j] && res[i+1][j] < res[i][j] + 1){//down
                res[i+1][j] = res[i][j] + 1;
            }
            if(j < n-1 && A[i][j] < A[i][j+1] && res[i][j+1] < res[i][j] + 1){//right
                res[i][j+1] = res[i][j] + 1;
            }
            maxres = max(maxres,res[i][j]);
        }
        
        return maxres;
    }
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值