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.

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/6405207.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值