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
原创粉丝点击