题解 | #训练聪明的牛II# DP

训练聪明的牛II

https://www.nowcoder.com/practice/79f86360f2894f76b88d33b28a5d09b8

知识点

动态规划

思路

状态表示: 定义 f[i] 为总和为i的最小个数,

状态转移: 每一次转移是选定当前选哪一个数字,即

f_i=min(\{f[i - w]\})+1

时间复杂度为 O(n)

AC Code (C++)

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param weights int整型vector 
     * @param totalWeight int整型 
     * @return int整型
     */
    const int INF = 1e9;
    int minEatTimes(vector<int>& weights, int totalWeight) {
        vector<int> f(totalWeight + 1, INF);
        f[0] = 0;
        for (int i = 1; i <= totalWeight; i ++) {
            for (auto x : weights) {
                if (i >= x) f[i] = min(f[i - x] + 1, f[i]);
            }
        }
        return f[totalWeight] == INF ? -1 : f[totalWeight];
    }
};

全部评论

相关推荐

07-02 13:52
武汉大学 golang
骗你的不露头也秒
牛客87776816...:😃查看图片
点赞 评论 收藏
分享
05-11 20:45
门头沟学院 Java
有担当的灰太狼又在摸...:零帧起手查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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