329 Longest Increasing Path in a Matrix
1. Question
Example 1:
Input:
nums =
[
[9,9,4],
[6,6,8],
[2,1,1]
]
Output: 4
Explanation:
The longest increasing path is [1, 2, 6, 9].Example 2:
Input:
nums =
[
[3,4,5],
[3,2,6],
[2,2,1]
]
Output:4
Explanation:
The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.2. Implementation(1) Memoization
思路: 从matrix的每个点作为起点,通过DFS找出所有可能的递增路径,然后找到最长的路径。但我们发现,DFS的过程会有很多重复计算,所以我们通过一个m * n的2维矩阵cache来存储每个点上的最长路径值,这样就可以保证每个点最多只计算一次
3. Time & Space Complexity
Memoization: 时间复杂度O(mn), 空间复杂度O(mn)
Last updated
Was this helpful?