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 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 几个技巧,教你去除文章的 AI 味!
· 系统高可用的 10 条军规
· 对象命名为何需要避免'-er'和'-or'后缀
· 关于普通程序员该如何参与AI学习的三个建议以及自己的实践
· AI与.NET技术实操系列(八):使用Catalyst进行自然语言处理