烹饪料理
难度:
标签:
题目描述
English description is not available for the problem. Please switch to Chinese.
代码结果
运行时间: 23 ms, 内存: 16.2 MB
/*
* 思路:
* 1. 使用Java Stream API来实现对食材组合的检查。
* 2. 对每种组合,检查是否满足饱腹感要求。
* 3. 记录满足条件的组合的最大美味度。
*/
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class MaxDeliciousnessStream {
public int getMaxDeliciousness(int[] materials, int[][] cookbooks, int[][] attribute, int limit) {
List<int[]> recipes = Arrays.stream(cookbooks).collect(Collectors.toList());
return recipes.stream()
.filter(recipe -> canCook(materials, recipe))
.mapToInt(recipe -> calculateMaxDeliciousness(materials, cookbooks, attribute, limit, recipe))
.max()
.orElse(-1);
}
private boolean canCook(int[] materials, int[] recipe) {
return IntStream.range(0, materials.length).allMatch(i -> materials[i] >= recipe[i]);
}
private int calculateMaxDeliciousness(int[] materials, int[][] cookbooks, int[][] attribute, int limit, int[] selectedRecipe) {
int[] remainingMaterials = Arrays.copyOf(materials, materials.length);
for (int i = 0; i < selectedRecipe.length; i++) {
remainingMaterials[i] -= selectedRecipe[i];
}
int totalDeliciousness = Arrays.stream(attribute).mapToInt(attr -> attr[0]).sum();
int totalSatisfaction = Arrays.stream(attribute).mapToInt(attr -> attr[1]).sum();
if (totalSatisfaction >= limit) {
return totalDeliciousness;
}
return -1;
}
}
解释
方法:
该题解采用了深度优先搜索(DFS)的方法来遍历所有可能的料理组合。通过递归探索制作每种料理的可能性,并对每种组合的饱腹感和美味度进行累加。当所有食材都足够时,检查当前的饱腹感是否满足限制条件,如果满足,则将当前的美味度加入到结果列表中。最终,从结果列表中取最大值作为答案。如果列表为空,表示没有任何料理组合能满足饱腹感要求,此时返回-1。
时间复杂度:
O(2^N)
空间复杂度:
O(N)
代码细节讲解
🦆
题解中提到使用深度优先搜索(DFS),请问为什么选择DFS而不是动态规划或贪心算法来解决这个问题?
▷🦆
在DFS的实现中,如何确保每次递归时食材数组`materials`不会被前一状态错误地修改影响后续递归?
▷🦆
题解中提到了如果`lim`大于等于`limit`就将`sums`添加到结果列表`path`,为什么不是在递归结束时才检查`lim`是否满足条件?
▷