#include <climits>
#include <vector>
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param weights int整型vector
     * @param totalWeight int整型
     * @return int整型
     */
    int minEatTimes(vector<int>& weights, int totalWeight) {
        // write code here
        const int inf = 0x3f3f3f;
        vector<int>dp(totalWeight + 1, inf);
        dp[0] = 0;
        int n = weights.size();
        for (int i : weights) {
            for (int j = i; j <= totalWeight; ++j) {
                if (dp[j - i] != inf)
                    dp[j] = min(dp[j], dp[j - i] + 1);
            }
        }
        if (dp[totalWeight] == inf)
            return -1;
        else
            return dp[totalWeight];
    }
};

一、题目考察的知识点

dp

二、题目解答方法的文字分析

初始化数组,并不断维护dp【i】的值,如果之前的状态已经不是初始状态那么表明当前已经达到了目标状态,那么就加上当前草料的重量

最后判断dp[totalWeight]的值就行

三、本题解析所用的编程语言

c++