题目考察的知识点

考察动态规划算法的应用

题目解答方法的文字分析

创建dp数组,其中dp[i]表示的是达到重量i所需的草料数。双重循环判断,内层循环遍历重量列表,根据题意找最小值,直到最后如果f[totalWeight] > totalWeight 说明无法凑出这个重量。

本题解析所用的编程语言

使用Java解答

完整且正确的编程代码

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param weights int整型一维数组
     * @param totalWeight int整型
     * @return int整型
     */
    public int minEatTimes (int[] weights, int totalWeight) {
        // write code here
        int[] f = new int[totalWeight + 1];
        Arrays.fill(f, totalWeight + 1);
        f[0] = 0;
        for (int i = 1; i <= totalWeight; i++) {
            for (int weight : weights) {
                if (weight <= i) {
                    f[i] = Math.min(f[i], f[i - weight] + 1);
                }
            }
        }
        return f[totalWeight] > totalWeight ? -1 : f[totalWeight];
    }
}