import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param weights int整型一维数组
* @param totalWeight int整型
* @return int整型
*/
public int minEatTimes (int[] weights, int totalWeight) {
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];
}
}
本题知识点分析:
1.动态规划
2.API函数
3.数学模拟
4.数组遍历
本题解题思路分析:
1.dp数组是什么,用于记录吃掉不同重量食物所需的最小次数
2.dp数组初始化,dp[0] = 0,表示吃掉重量为0的食物需要的次数
3.如果weight小于等于当前重量i,表示食物可以添加,更新次数
4.最后如果最后一个索引位置大于totalWeight,表示无法吃掉,返回-1,否则返回最后一个索引位置

京公网安备 11010502036488号