题目考察的知识点是:
动态规划。
题目解答方法的文字分析:
先定义一个新的数组,将数据放入新的数组中,使用两个循环去判断,获取到最小的值,最后使用三元运算符得到最后的结果。
本题解析所用的编程语言:
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];
}
}

京公网安备 11010502036488号