码迷,mamicode.com
首页 > 其他好文 > 详细

0/1背包问题

时间:2019-06-30 09:35:15      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:ready   str   check   from   font   osi   rgs   exce   public   

 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背包问题

标签:ready   str   check   from   font   osi   rgs   exce   public   

原文地址:https://www.cnblogs.com/patrick-tech/p/11108533.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!