動態規劃 VS 記憶化搜索

  • 記憶化搜素=搜索的形式+動態規劃的思想
  • 動態規劃適用於:要使用的子問題的值已經被確定,不會再被更新的情況
  • 適合動態規劃的都適合記憶化搜索,反之不然
  • 思想:在搜索過程中,會有很多重複計算,如果我們能記錄一些狀態的答案,就可以減少重複搜索量
  • 適用範圍:解決重複計算,不適合單純生成一個走步方案,而是適合生成一個走步方案的代價
  • 核心實現
    • 一個表記錄已經存儲下的搜索結果
    • 狀態存儲
    • 如果狀態出現過則直接調用結果,沒有出現過則正常搜索

參考鏈接:

https://blog.csdn.net/hjf1201/article/details/78680814

https://blog.csdn.net/qq_41289920/article/details/80691537

例題:

https://leetcode-cn.com/explore/interview/card/top-interview-quesitons-in-2018/272/dynamic-programming/1181/

//矩陣中的最長遞增路徑,可以向上下左右四個方向走
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;
    }
};

 

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