【Lintcode】398. Longest Continuous Increasing Subsequence II

記錄演算法發表於2020-10-01

題目地址:

https://www.lintcode.com/problem/longest-continuous-increasing-subsequence-ii/description

給定一個二維矩陣 A A A,從某個位置出發,可以向上下左右走一步。問由嚴格上升數字構成的最長路徑的長度。

思路是記憶化搜尋。設 f [ i ] [ j ] f[i][j] f[i][j]是從 A [ i ] [ j ] A[i][j] A[i][j]出發的最長上升路徑的長度,則 f [ i ] [ j ] f[i][j] f[i][j]可以由 1 1 1加上四周比 A [ i ] [ j ] A[i][j] A[i][j]大的數出發的最長上升路徑的長度來更新。如果不存在,那麼 f [ i ] [ j ] = 1 f[i][j]=1 f[i][j]=1。程式碼如下:

public class Solution {
    /**
     * @param matrix: A 2D-array of integers
     * @return: an integer
     */
    public int longestContinuousIncreasingSubsequence2(int[][] matrix) {
        // write your code here
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return 0;
        }
        
        int m = matrix.length, n = matrix[0].length;
        int[][] dp = new int[m][n];
        
        int res = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                res = Math.max(res, dfs(i, j, dp, matrix));
            }
        }
        
        return res;
    }
    
    private int dfs(int x, int y, int[][] dp, int[][] matrix) {
    	// 有記憶,則調取記憶
        if (dp[x][y] != 0) {
            return dp[x][y];
        }
        
        // 先初始化為1
        dp[x][y] = 1;
        int[] d = {1, 0, -1, 0, 1};
        for (int i = 0; i < 4; i++) {
            int nextX = x + d[i], nextY = y + d[i + 1];
            // 如果沒出界,並且可以接上去,就繼續DFS
            if (0 <= nextX && nextX < matrix.length && 0 <= nextY && nextY < matrix[0].length && matrix[nextX][nextY] > matrix[x][y]) {
                dp[x][y] = Math.max(dp[x][y], 1 + dfs(nextX, nextY, dp, matrix));
            }
        }
        
        return dp[x][y];
    }
}

時空複雜度 O ( m n ) O(mn) O(mn)

相關文章