leetcode 329. 矩陣中的最長遞增路徑(記憶化搜尋)
阿新 • 來源:網路 • 發佈:2021-05-26
題目描述
給定一個 m x n 整數矩陣 matrix ,找出其中 最長遞增路徑 的長度。
對於每個單元格,你可以往上,下,左,右四個方向移動。 你 不能 在 對角線 方向上移動或移動到 邊界外(即不允許環繞)。
示例 1:
輸入:matrix = [[9,9,4],[6,6,8],[2,1,1]]
輸出:4

解釋:最長遞增路徑為 [1, 2, 6, 9]。
示例 2:
輸入:matrix = [[3,4,5],[3,2,6],[2,2,1]]
輸出:4
解釋:最長遞增路徑是 [3, 4, 5, 6]。注意不允許在對角線方向上移動。
示例 3:
輸入:matrix = [[1]]
輸出:1
該題目與【滑雪】題目類似,使用的是記憶化搜尋,記憶化搜尋用到的是是dfs 遞迴以及動態規劃方式的結合,使用記憶化就是將結果儲存起來,並且後續的遍歷不會影響到該結果,且在遍歷過程中不存在環,如果存在環就無法使用動態規劃了。以下是記憶化搜尋的模板。記憶化搜尋詳細介紹
class Solution {
public:
int n,m;
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
vector<vector<int>> f,w;
int dp(int x,int y)
{
if(f[x][y]!=-1) return f[x][y];
f[x][y]=1;
for(int i=0;i< 4;i++)
{
int a = x+dx[i],b = y+dy[i];
if(a>=0&&a<n && b>=0 && b<m && w[x][y]>w[a][b])
{
f[x][y]=max(f[x][y],dp(a,b)+1);
}
}
return f[x][y];
}
int longestIncreasingPath(vector<vector<int>>& matrix) {
w = matrix;
n = w.size(),m = w[0].size();
f = vector<vector<int>>(n, vector<int>(m, -1));
int res=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
res=max(res,dp(i,j));
}
}
return res;
}
};
