滑雪dp

作者: ColdRomantic | 来源:发表于2020-07-03 17:38 被阅读0次

经典的dp题:滑雪-dp记忆化深搜

DP 记忆化深搜
(1) 如果只有1个点,结果就是1
(2) 如果有两个点,从1->2, 结果就是2
用f(i,j) 表示以(i,j)为终点的最长路径。
如果有多个点:
f(i, j) = max{从他周围的四个高处 过来 } + 1; 其中上下左右4个高处f(x,y)是个子问题。

#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
/**
 * DP 记忆化深搜
 * 把当前位置g[i][j]作为终点, f(i, j) = max{1, 从他周围的四个高处 过来 + 1}
 */
class Solution {
private:
    struct position{
        int x, y;
    };
    //右/下/左/上
    const position dir[] = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
public:
    //把当前位置g[i][j]作为终点, f(i, j) = max{1, 从他周围的四个高处 过来 + 1}
    int dp_search(vector<vector<int>>& graph, int i, int j, vector<vector<int>>& cache) {
        if (cache[i][j]) {
            return cache[i][j];
        }
        cache[i][j] = 1;
        for(int k = 0; k < 4; k++) {
            int x = i + dir[k].x;
            int y = j + dir[k].y;
            // valid coordinates
            if (x >= 0 && x < graph.size() && y >= 0 && y < graph[0].size()) {
                if (graph[x][y] > graph[i][j]) {
                    cache[i][j] = std::max(cache[i][j], dp_search(graph, x, y, cache) + 1);
                }
            }
        }
        return  cache[i][j];
    }

    int solution(vector<vector<int>> graph){
        if (graph.size() <= 0) {
            return 0;
        }
        int n = graph.size();
        int m = graph[0].size();
        vector<vector<int>> cache(n + 2, vector<int>(m + 2, 0));

        int max_path = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                cache[i][j] = dp_search(graph, i, j, cache);
                max_path = std::max(max_path, cache[i][j]);
            }
        }
        return max_path;
    }
};

相关文章

  • 滑雪dp

    经典的dp题:滑雪-dp记忆化深搜 DP 记忆化深搜(1) 如果只有1个点,结果就是1(2) 如果有两个点,从1-...

  • LeetCode-338-比特位计数

    解题思路: 枚举: dp[0]=0; dp[1]=1;dp[2]=1; dp[3]=2;dp[4]=1; dp[5...

  • MIT 动态规划算法笔记 DP

    DP: Dynamic Programming DP ≈ "Careful Brute foree" DP ≈ ...

  • 70. Climbing Stairs

    思路:dp[i] = dp[i - 1 ] + dp[i - 2];

  • 70. Climbing Stairs

    经典递归,dp[i] = dp[i-1]+dp[i-2],从0 算到n-1 ,返回dp[n-1] dp[0] = ...

  • DP小结

    DP种类 线性DP 区间DP 树形DP 背包DP01背包满背包完全背包(转成01背包) 例子:线性动规:拦截导弹,...

  • LeetCode 746. Min Cost Climbing

    DP解法:定义一个dp数组,dp[i]为到达第i层的最小花费,dp[i]仅与dp[i-1]和dp[i-2]和相应层...

  • 416. Partition Equal Subset Sum

    解题思路: 用双循环去更新dp[j]:dp[j] = dp[j] || dp[j - nums[i]] 代码: c...

  • 每日算法:

    动态规划: dp[i] = dp[i-1]>0?dp[i-1]+nums[i]:nums[i];dp[i]表示从...

  • 长度单位与内外边距

    dp=dip(Device Independent pixels)换算公式: px=dp*(dpi/160)在dp...

网友评论

      本文标题:滑雪dp

      本文链接:https://www.haomeiwen.com/subject/lbxeqktx.html