add 329. Longest Increasing Path in a Matrix 🍺

This commit is contained in:
ShusenTang 2020-04-06 21:53:41 +08:00
parent ce2a8171a0
commit cc3e99ab72
2 changed files with 41 additions and 0 deletions

View File

@ -235,6 +235,7 @@ My LeetCode solutions with Chinese explanation. 我的LeetCode中文题解。
| 324 |[Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/324.%20Wiggle%20Sort%20II.md)|Medium| |
| 326 |[Power of Three](https://leetcode.com/problems/power-of-three)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/326.%20Power%20of%20Three.md)|Easy| |
| 328 |[Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/328.%20Odd%20Even%20Linked%20List.md)|Medium| |
| 329 |[Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/)|[C++](solutions/329.%20Longest%20Increasing%20Path%20in%20a%20Matrix.md)|Hard| |
| 331 |[Verify Preorder Serialization of a Binary Tree](https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/331.%20Verify%20Preorder%20Serialization%20of%20a%20Binary%20Tree.md)|Medium| |
| 332 |[Reconstruct Itinerary](https://leetcode.com/problems/reconstruct-itinerary/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/332.%20Reconstruct%20Itinerary.md)|Medium| |
| 334 |[Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/334.%20Increasing%20Triplet%20Subsequence.md)|Medium| |

View File

@ -0,0 +1,40 @@
# [329. Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/)
# 思路
给定一个二维矩阵求矩阵中最长的递增路径。我们可以从尝试从每个位置出发进行DFS计算出以每个位置为起始的最长递增路径最后返回最长即可。注意到DFS会存在大量重复所以我们需要开辟一个二维记忆数组`cache``cache[i][j]`表示以位置ij为起始的最长递增路径长度初始为0。当我们进行DFS时如果发现`cache[i][j] > 0`,说明之前已经计算过了,无需再进行计算,直接返回`cache[i][j]`即可。
# C++
``` C++
class Solution {
private:
int m, n;
vector<vector<int>>cache;
int DFS(const vector<vector<int>>& matrix, int i, int j){
if(cache[i][j] > 0) return cache[i][j];
int sub_res = 0;
if(i > 0 && matrix[i-1][j] > matrix[i][j]) sub_res = max(sub_res, DFS(matrix, i-1, j));
if(j > 0 && matrix[i][j-1] > matrix[i][j]) sub_res = max(sub_res, DFS(matrix, i, j-1));
if(i < m-1 && matrix[i+1][j] > matrix[i][j]) sub_res = max(sub_res, DFS(matrix, i+1, j));
if(j < n-1 && matrix[i][j+1] > matrix[i][j]) sub_res = max(sub_res, DFS(matrix, i, j+1));
cache[i][j] = 1 + sub_res;
return cache[i][j];
}
public:
int longestIncreasingPath(vector<vector<int>>& matrix) {
m = matrix.size();
if(!m) return 0;
n = matrix[0].size();
cache = vector<vector<int>>(m, vector<int>(n, 0));
int res = 0;
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
res = max(res, DFS(matrix, i, j));
return res;
}
};
```