zoukankan      html  css  js  c++  java
  • LintCode Longest Increasing Continuous subsequence II

    原题链接在这里:http://www.lintcode.com/en/problem/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).

    Example

    Given a matrix:

    [
      [1 ,2 ,3 ,4 ,5],
      [16,17,24,23,6],
      [15,18,25,22,7],
      [14,19,20,21,8],
      [13,12,11,10,9]
    ]
    

    return 25

    题解:

    DP. 状态是当前点为结束点,能有的最长延展长度. 转移方程是若周围四个方向有比我小的, 取符合条件的较大长度加1 dp[i][j] = Math.max(dp[dx][dy])+1.

    但问题是如何按照由大到小的方向iterate 矩阵, 可以使用dfs.

    Time Complexity: O(m * n), 每个点最多走两遍.

    Space: O(m * n).

    AC Java:

     1 public class Solution {
     2     public int longestIncreasingContinuousSubsequenceII(int[][] A) {
     3         if(A == null || A.length == 0|| A[0].length == 0){
     4             return 0;
     5         }
     6         
     7         int res = 1;
     8         int m = A.length;
     9         int n = A[0].length;
    10         int [][] dp = new int[m][n];
    11         boolean [][] visited = new boolean[m][n];
    12         for(int i = 0; i<m; i++){
    13             for(int j = 0; j<n; j++){
    14                 dp[i][j] = dfs(A, i, j, visited, dp);
    15                 res = Math.max(res, dp[i][j]);
    16             }
    17         }
    18         return res;
    19     }
    20     
    21     int [][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    22     private int dfs(int [][] A, int i, int j, boolean [][] visited, int [][] dp){
    23         if(visited[i][j]){
    24             return dp[i][j];
    25         }
    26         
    27         int res = 1;
    28         int m = A.length;
    29         int n = A[0].length;
    30         for(int [] dir : dirs){
    31             int dx = i + dir[0];
    32             int dy = j + dir[1];
    33             if(dx>=0 && dx<m && dy>=0 && dy<n && A[i][j]>A[dx][dy]){
    34                 res = Math.max(res, dfs(A, dx, dy, visited, dp)+1);
    35             }
    36         }
    37         visited[i][j] = true;
    38         dp[i][j] = res;
    39         return res;
    40     }
    41 }

    类似Longest Increasing Continuous Subsequence.

  • 相关阅读:
    ajax同步和异步
    vue组件
    type of的返回值有哪些
    git配置
    vue 获取时间戳对象转换为日期格式
    JavaScript运行机制
    单页面开发首屏加载慢,白屏如何解决
    单页面和多页面开发的优缺点
    【安全测试】sql注入
    【Python学习一】使用Python+selenium实现第一个自动化测试脚本
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/6405207.html
Copyright © 2011-2022 走看看