0-1背包问题
来源:互联网 发布:h5 js 打开支付宝app 编辑:程序博客网 时间:2024/05/23 15:12
0-1背包问题是很经典的一个题目。
具体细节再次不叙了。
本文给出动态编程解法。
public class Knapsack {public static void main(String[] args) {int c = 10;int[] weights = { 2, 2, 6, 5, 4 };int[] prices = { 6, 3, 5, 4, 6 };System.out.println(knapsackDP(weights, prices, c));}private static void print(int[][] table) {int m = table.length;int n = table[0].length;for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {System.out.print(table[i][j] + " ");}System.out.println();}}/** * knapsack problem * * */public static int knapsackDP(int[] weights, int[] prices, int capcity) {int M = weights.length;int N = capcity;// item * weightint[][] table = new int[M + 1][N + 1];// initfor (int i = 0; i <= M; i++)table[i][0] = 0;for (int i = 0; i <= N; i++)table[0][i] = 0;for (int i = 1; i <= M; i++) {for (int j = 1; j <= N; j++) {if (j >= weights[i - 1]) {table[i][j] = Math.max(table[i - 1][j - weights[i - 1]]+ prices[i - 1], table[i - 1][j]);} else {table[i][j] = table[i - 1][j];}}}print(table);return table[M][N];}}
输出:
0 0 0 0 0 0 0 0 0 0 0
0 0 6 6 6 6 6 6 6 6 6
0 0 6 6 9 9 9 9 9 9 9
0 0 6 6 9 9 9 9 11 11 14
0 0 6 6 9 9 9 10 11 13 14
0 0 6 6 9 9 12 12 15 15 15
15
0 0
- 背包问题(0-1背包、完全背包、多重背包)详解
- 背包问题和0-1背包问题
- 背包问题和0-1背包问题
- 背包问题系列--"0-1背包问题"
- 背包笔记-含0/1背包问题、完全背包问题、多重背包问题、二维背包问题、分组背包问题
- 【背包问题】背包问题之0-1背包、完全背包、多重背包
- 0-1背包问题
- 0/1背包问题
- 0,1背包问题
- 0-1背包问题
- 0/1背包问题
- 0-1背包问题
- // 0-1背包问题
- 0/1背包问题
- 0-1背包问题
- 0-1背包问题
- 0-1背包问题
- 0/1背包问题
- <meta property="og:需要写的标签"的应用
- android Log控制小技巧--BuildConfig.DEBUG的使用
- js中 location对象的使用
- HTTP 1.1与HTTP 1.0的比较 -- linux内核
- GCD使用攻略
- 0-1背包问题
- popcorn maker在线视频编辑工具的配置及相关设置
- Best Time to Buy and Sell Stock III
- 分析一下B2B网站运营的几点要求
- hub_config
- Socket网络编程之Client端
- volley应用及例子
- shiro学习与应用
- Socket和Http通信