01背包问题 java

这篇博客介绍了01背包问题,这是一个经典的动态规划问题。通过动态规划的方法,逐步填充一个表格,以找到在有限容量的背包中最大化物品价值的解决方案。博主详细解释了动态规划的思路,并给出了具体的计算过程,最终得出背包能容纳的最大价值为22。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

01背包问题是动态规划中的经典问题

一、问题描述:有n 个物品,它们有各自的重量和价值,现有给定容量的背包,如何让背包里装入的物品具有最大的价值总和?

 

解决这个题有两种方法,和其它的动态规划问题一样

数组w[]为物品的重量,v[]为物品的价值

一种是递归的思想,从后向前考虑,背包决定是否放一个物品是根据两个值的大小判断(一个值是背包没有放入这个物品的价值,另一个值是背包放入这个物品,另外背包容量减少物品重量的价值),去两个值中的最大值,递归结束条件是物品放完或者是背包容量小于等于0

量化为公式就是

    public int recursiveBackpack1(int[] w, int[] v, int size) {
        if (w.length != v.length) return -1;
        int n = w.length;
        return bestValue1(w, v, n - 1, size);
    }

    private int bestValue1(int[] w, int[] v, int index, int size) {
        if (index < 0 || size <= 0) return 0;

        int res = bestValue1(w, v, index - 1, size);
        if (size >= w[index]) {
            res = max(v[index] + bestValue1(w, v, index - 1, size - w
### 0-1 背包问题Java 实现解决方案 #### 动态规划方法 动态规划是一种经典的解决 0-1 背包问题的方法。它通过构建一个二维数组 `dp` 来存储子问题的结果,其中 `dp[i][j]` 表示前 `i` 个物品背包容量为 `j` 的情况下的最大价值。 以下是基于动态规划的 Java 实现: ```java public class Knapsack { public static int knapSack(int W, int[] wt, int[] val, int n) { int[][] dp = new int[n + 1][W + 1]; for (int i = 0; i <= n; i++) { for (int w = 0; w <= W; w++) { if (i == 0 || w == 0) { dp[i][w] = 0; } else if (wt[i - 1] <= w) { dp[i][w] = Math.max(val[i - 1] + dp[i - 1][w - wt[i - 1]], dp[i - 1][w]); } else { dp[i][w] = dp[i - 1][w]; } } } return dp[n][W]; } public static void main(String[] args) { int[] val = {60, 100, 120}; int[] wt = {10, 20, 30}; int W = 50; int n = val.length; System.out.println(knapSack(W, wt, val, n)); // 输出结果应为 220 } } ``` 上述代码实现了动态规划的核心逻辑[^4]。通过迭代计算每个状态的最大价值,最终得到全局最优解。 --- #### 递归方法 递归方法可以通过回溯的思想解决问题。对于每一个物品,可以选择将其放入背包或者不放入背包,从而形成两种可能的状态树。递归方法的时间复杂度较高,但由于其简单直观,在某些场景下仍然具有应用价值。 以下是基于递归的 Java 实现: ```java public class RecursiveKnapsack { public static int knapSack(int W, int[] wt, int[] val, int n) { if (n == 0 || W == 0) { return 0; } if (wt[n - 1] > W) { return knapSack(W, wt, val, n - 1); } else { return Math.max( val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1), knapSack(W, wt, val, n - 1) ); } } public static void main(String[] args) { int[] val = {60, 100, 120}; int[] wt = {10, 20, 30}; int W = 50; int n = val.length; System.out.println(knapSack(W, wt, val, n)); // 输出结果应为 220 } } ``` 此代码展示了递归方法的基本思想[^1]。尽管这种方法易于理解,但在大规模数据集上可能会遇到性能瓶颈。 --- #### 分支限界法 分支限界法通过对搜索空间进行剪枝优化,减少不必要的计算量。该方法通常用于处理较大规模的数据集,并能有效降低时间复杂度。 以下是一个简单的分支限界法实现思路: ```java import java.util.*; public class BranchAndBoundKnapsack { private static class Node implements Comparable<Node> { int level, profit, bound, weight; @Override public int compareTo(Node other) { return Double.compare(other.bound, this.bound); // 按照边界值降序排列 } } public static int solveKnapsack(int capacity, int[] weights, int[] values, int itemCount) { PriorityQueue<Node> pq = new PriorityQueue<>(); double totalProfit = Arrays.stream(values).sum(); Node root = new Node(); root.level = -1; root.profit = 0; root.weight = 0; computeBound(root, capacity, weights, values, itemCount); pq.add(root); while (!pq.isEmpty()) { Node node = pq.poll(); if (node.bound > maxProfit && node.weight <= capacity) { maxProfit = node.profit; } if (node.level >= itemCount - 1) continue; Node nextInclude = new Node(); nextInclude.level = node.level + 1; nextInclude.weight = node.weight + weights[nextInclude.level]; nextInclude.profit = node.profit + values[nextInclude.level]; if (nextInclude.weight <= capacity && nextInclude.profit > maxProfit) { maxProfit = nextInclude.profit; } computeBound(nextInclude, capacity, weights, values, itemCount); if (nextInclude.bound > maxProfit) { pq.add(nextInclude); } Node nextExclude = new Node(); nextExclude.level = node.level + 1; nextExclude.weight = node.weight; nextExclude.profit = node.profit; computeBound(nextExclude, capacity, weights, values, itemCount); if (nextExclude.bound > maxProfit) { pq.add(nextExclude); } } return maxProfit; } private static void computeBound(Node u, int cap, int[] wt, int[] val, int n) { if (u.weight >= cap) { u.bound = 0; return; } u.bound = u.profit; int j = u.level + 1; int totweight = u.weight; while ((j < n) && (totweight + wt[j] <= cap)) { totweight += wt[j]; u.bound += val[j]; j++; } if (j < n) { u.bound += (cap - totweight) * (val[j] / (double) wt[j]); } } private static int maxProfit = Integer.MIN_VALUE; public static void main(String[] args) { int[] val = {60, 100, 120}; int[] wt = {10, 20, 30}; int W = 50; int n = val.length; System.out.println(solveKnapsack(W, wt, val, n)); // 输出结果应为 220 } } ``` 这段代码采用了优先队列来管理节点的选择顺序,并通过边界值计算加速收敛过程[^5]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值