题解 | #牛牛的跳跃挑战# 线性DP

牛牛的跳跃挑战

https://www.nowcoder.com/practice/0c99c2161c2d4a4e91ca55363cc0e059

知识点

动态规划

思路

定义f[i]为到达下标为i位置所需要的最小的代价, 答案为f[n]

每一次可以从前面3个位置进行转移

时间复杂度 O(n)

AC Code (C++)

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param height int整型vector 
     * @return int整型
     */
    const int INF = 1e9;
    int minEnergyJump(vector<int>& height) {
        int n = height.size();
        vector<int> f(n + 1, INF);
        f[0] = f[1] = f[2] = 0;
        for (int i = 3; i <= n; i ++) {
            for (int j = max(0, i - 3); j < i; j ++) {
                f[i] = min(f[i], f[j] + height[j]);
            }
        }
        return f[n];
    }
};

全部评论

相关推荐

见见123:简历没有啥问题,是这个社会有问题。因为你刚毕业,没有工作经历,现在企业都不要没有工作经历的。社会病了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务