Leetcode刷題java之329. 矩陣中的最長遞增路徑(一天一道編程題之五十天)

執行結果:

通過

顯示詳情

執行用時 :11 ms, 在所有 Java 提交中擊敗了73.70% 的用戶

內存消耗 :39.7 MB, 在所有 Java 提交中擊敗了53.41%的用戶

題目:

給定一個整數矩陣,找出最長遞增路徑的長度。

對於每個單元格,你可以往上,下,左,右四個方向移動。 你不能在對角線方向上移動或移動到邊界外(即不允許環繞)。

示例 1:

輸入: nums = 
[
  [9,9,4],
  [6,6,8],
  [2,1,1]

輸出: 4 
解釋: 最長遞增路徑爲 [1, 2, 6, 9]。

示例 2:

輸入: nums = 
[
  [3,4,5],
  [3,2,6],
  [2,2,1]

輸出: 4 
解釋: 最長遞增路徑是 [3, 4, 5, 6]。注意不允許在對角線方向上移動。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/longest-increasing-path-in-a-matrix
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

思路:

採用回溯法+記憶化,因爲有一些位置已經計算過了,就不必再計算了,用一個緩存來記錄這個位置開始的遞增序列的長度

代碼:

// DFS + Memoization Solution
// Accepted and Recommended
public class Solution {
    private static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    private int m, n;

    public int longestIncreasingPath(int[][] matrix) {
        if (matrix.length == 0) return 0;
        m = matrix.length; n = matrix[0].length;
        int[][] cache = new int[m][n];
        int ans = 0;
        for (int i = 0; i < m; ++i)
            for (int j = 0; j < n; ++j)
                ans = Math.max(ans, dfs(matrix, i, j, cache));
        return ans;
    }

    private int dfs(int[][] matrix, int i, int j, int[][] cache) {
        if (cache[i][j] != 0) return cache[i][j];
        for (int[] d : dirs) {
            int x = i + d[0], y = j + d[1];
            if (0 <= x && x < m && 0 <= y && y < n && matrix[x][y] > matrix[i][j])
                cache[i][j] = Math.max(cache[i][j], dfs(matrix, x, y, cache));
        }
        return ++cache[i][j];
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章