java解决01背包问题示例代码
代码语言:java
所属分类:算法
代码描述:java解决01背包问题示例代码,01背包问题就是你需要选择一组物品放入一个背包,以使它们的总价值最大化,同时不超过背包的容量限制。
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
import java.util.ArrayList; import java.util.List; public class HelloWorld { public static void main(String[] args) { int[] values = {60, 100, 120}; int[] weights = {10, 20, 30}; int capacity = 50; int[] selectedItems = knapsack(values, weights, capacity); System.out.println("Maximum value: " + selectedItems[selectedItems.length - 1]); System.out.println("Selected items: "); for (int i = 0; i < selectedItems.length - 1; i++) { System.out.println(selectedItems[i] + " "); } } public static int[] knapsack(int[] values, int[] weights, int capacity) { int n = values.length; int[][] dp = new int[n + 1][capacity + 1]; for (int i = 1; i <= n; i++) { for (int w = 1; w <= capacity; w++) { if (weights[i - 1] <= w) { .........完整代码请登录后点击上方下载按钮下载查看
网友评论0