Java解决01背包问题

import java.util.Arrays;

public class Knapsack_01 {
	public static void main(String[] args) {
		int[] w = { 1, 5, 1 };
		int[] v = { 3, 2, 2};
		int C = 3;
		int n = w.length;
		int[][] F = new int[n + 1][C + 1];
		int[][] P = new int[n + 1][C + 1];
		for (int i = 1; i <= n; i++) {
			for (int j = 1; j <= C; j++) {
				if (j < w[i - 1]) {
					F[i][j] = F[i - 1][j];
					P[i][j] = P[i - 1][j];
				} else {
					F[i][j] = F[i - 1][j - w[i - 1]] + v[i - 1];
					P[i][j] = i;
					if (F[i - 1][j] >= F[i][j]) {
						F[i][j] = F[i - 1][j];
						P[i][j] = P[i - 1][j];
					}
				}
			}
		}
		System.out.println("背包中物品的最大的总价值为:" + F[n][C]);
		int[] x = new int[n];
		for (int i = n, j = C; i >= 1; i--) {
			if (P[i][j] == 0) {
				break;
			}
			x[P[i][j] - 1] = 1;
			j = j - w[P[i][j] - 1];
		}
		System.out.println("选择的物品为:" + Arrays.toString(x));
	}

}

运行结果截图:

Java解决01背包问题_第1张图片

你可能感兴趣的:(Java)