0/1背包问题

Posted patrick-tech

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了0/1背包问题相关的知识,希望对你有一定的参考价值。

 1 public class ZeroOneKnapsack 
 2 
 3   public int solveKnapsack(int[] profits, int[] weights, int capacity) 
 4     Integer[][] dp = new Integer[profits.length][capacity + 1];
 5     return this.knapsackRecursive(dp, profits, weights, capacity, 0); 
 6   
 7   private int knapsackRecursive(Integer[][] dp, int[] profits, int[] weights, int capacity,
 8       int currentIndex) 
 9 
10     // base checks
11     if (capacity <= 0 || currentIndex >= profits.length)
12       return 0;
13 
14     // if we have already solved a similar problem, return the result from memory
15     if(dp[currentIndex][capacity] != null)
16       return dp[currentIndex][capacity];
17 
18     // recursive call after choosing the element at the currentIndex
19     // if the weight of the element at currentIndex exceeds the capacity, we shouldn‘t process this
20     int profit1 = 0;
21     if( weights[currentIndex] <= capacity )
22         profit1 = profits[currentIndex] + knapsackRecursive(dp, profits, weights,
23                 capacity - weights[currentIndex], currentIndex + 1);
24 
25     // recursive call after excluding the element at the currentIndex
26     int profit2 = knapsackRecursive(dp, profits, weights, capacity, currentIndex + 1);
27 
28     dp[currentIndex][capacity] = Math.max(profit1, profit2);
29     return dp[currentIndex][capacity];
30   
31   
32   
33   
34   public static void main(String[] args) 
35     ZeroOneKnapsack ks = new ZeroOneKnapsack();
36     int[] profits = 1, 6, 10, 16;
37     int[] weights = 1, 2, 3, 5;
38     int maxProfit = ks.solveKnapsack(profits, weights, 7);
39     System.out.println("Total knapsack profit ---> " + maxProfit);
40     maxProfit = ks.solveKnapsack(profits, weights, 6);
41     System.out.println("Total knapsack profit ---> " + maxProfit);
42   
43 

以上是关于0/1背包问题的主要内容,如果未能解决你的问题,请参考以下文章

C++ 算法主题系列之集结0-1背包问题的所有求解方案

动态规划-多重背包问题

背包问题(0-1背包+完全背包)

0-1背包问题 —— 四种解法解题

背包问题之0-1背包

背包0-1背包与完全背包一维数组实现