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).this
Example
Given a matrix:spa[ [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 25Challenge
O(nm)
time and memory.code
這題很是像經典的滑雪問題,解決方法都是DFS + Memorization. dp[i][j]
表示以點(i, j)
爲起始點的連續子序列最大長度。dp[i][j]
的值能夠根據其符合要求的鄰居的dp值推出,根據dp值,咱們維護一個全局的最大值,具體見代碼。it
time: O(mn), space: O(mn)io
public class Solution { public int longestIncreasingContinuousSubsequenceII(int[][] A) { int rows = A.length; if (rows == 0) return 0; int cols = A[0].length; boolean[][] visited = new boolean[rows][cols]; int[][] dp = new int[rows][cols]; int max = 1; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (dp[i][j] == 0) dfs(A, visited, dp, i, j); max = Math.max(max, dp[i][j]); } } return max; } public void dfs(int[][] A, boolean[][] visited, int[][] dp, int row, int col) { if (visited[row][col]) return; visited[row][col] = true; int[][] dirs = new int[][]{{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; int max = 0; // 對符合要求的鄰居分別DFS for (int i = 0; i < dirs.length; i++) { int x = row + dirs[i][0]; int y = col + dirs[i][1]; if (x >= 0 && x < dp.length && y >= 0 && y < dp[0].length && A[x][y] > A[row][col]) { dfs(A, visited, dp, x, y); max = Math.max(max, dp[x][y]); } } dp[row][col] = max + 1; // 根據鄰居DFS後最大值更新本身的值 } }