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.

posted @   Dylan_Java_NYC  阅读(730)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
阅读排行:
· 几个技巧,教你去除文章的 AI 味!
· 系统高可用的 10 条军规
· 对象命名为何需要避免'-er'和'-or'后缀
· 关于普通程序员该如何参与AI学习的三个建议以及自己的实践
· AI与.NET技术实操系列(八):使用Catalyst进行自然语言处理
点击右上角即可分享
微信分享提示