- 记忆化搜素=搜索的形式+动态规划的思想
- 动态规划适用于:要使用的子问题的值已经被确定,不会再被更新的情况
- 适合动态规划的都适合记忆化搜索,反之不然
- 思想:在搜索过程中,会有很多重复计算,如果我们能记录一些状态的答案,就可以减少重复搜索量
- 适用范围:解决重复计算,不适合单纯生成一个走步方案,而是适合生成一个走步方案的代价
- 核心实现
- 一个表记录已经存储下的搜索结果
- 状态存储
- 如果状态出现过则直接调用结果,没有出现过则正常搜索
参考链接:
https://blog.csdn.net/hjf1201/article/details/78680814
https://blog.csdn.net/qq_41289920/article/details/80691537
例题:
//矩阵中的最长递增路径,可以向上下左右四个方向走
class Solution {
public:
int n, m;
vector<vector<int>> f, g;
int next[4][2]={1,0,-1,0,0,-1,0,1};
int dp(int x, int y)
{
if (f[x][y] != -1) return f[x][y];//记忆话搜索的的核心,搜过就标记,避免重复搜索。
f[x][y] = 1;//注意这里要初始化为1 标记为搜索过
for (int i = 0; i < 4; i ++ )
{
int a=x+next[i][0];
int b=y+next[i][1];
if (a >= 0 && a < n && b >= 0 && b < m && g[a][b] < g[x][y])
f[x][y] = max(f[x][y], dp(a, b) + 1);
}
return f[x][y];
}
int longestIncreasingPath(vector<vector<int>>& matrix) {
if (matrix.empty()) return 0;
g = matrix;
n = g.size(), m = g[0].size();
f = vector<vector<int>>(n, vector<int>(m, -1));
int res = 1;
for (int i = 0; i < n; i ++ )
for (int j = 0; j < m; j ++ )
res = max(res, dp(i, j));
return res;
}
};