01背包问题java

01背包问题java_第1张图片

方程为:b[j]=Math.max( b[j],b[j-w[i]]+v[i])

01背包问题java_第2张图片

优化前的代码如下:

import java.util.Scanner;
/**
 * 01背包问题
 * @author Administrator
 *
 */
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int target = sc.nextInt();
		int[] weight = new int[n];
		int[] value = new int[n];
		for (int i = 0; i < n; i++) {
			weight[i] = sc.nextInt();
			value[i] = sc.nextInt();
		}
		int res = maxValue(n,target, weight, value);
		System.out.println(res);
	}	
	
	public static int maxValue(int n,int target,int[] w,int[] v) {
		int[][] arr = new int[n][target+1];
		for (int i = 0; i <= target; i++) {
			if(i>=w[0]) {
				arr[0][i]=v[0];
			}
		}
		for (int i = 1; i < n; i++) {
			for (int j = 0; j <= target; j++) {
			    if(j

 

你可能感兴趣的:(Java)