揹包问题简单示例

package knapsack;
//简单揹包问题示例
public class Knapsack {
	public static void main(String[] args){
        int val[] = {10, 40, 30, 50};//物品的价值
        int wt[] = {5, 4, 6, 3};//物品的重量
        int W = 10;//重量限制
        System.out.println(knapsack(val, wt, W));
    }
	 public static int knapsack(int val[], int wt[], int W) {
	    int N = wt.length;
	    int[][] V = new int[N + 1][W + 1];
	    for (int col = 0; col <= W; col++) {
	    	V[0][col] = 0;
	    }//没有物品放入时,价值全为0
	    for (int row = 0; row <= N; row++) {
	        V[row][0] = 0;
	    }//重量限制为0时,价值全为0
	    for (int item=1;item<=N;item++){
	    	for (int weight=1;weight<=W;weight++){
	    		if (wt[item-1]<=weight){
	    			V[item][weight]=Math.max (val[item-1]+V[item-1][weight-wt[item-1]], V[item-1][weight]);
	            }//核心代码:放入第item个物品+前一行剩余重量的局部解,和前一行相同重量的局部解比较,取最大值(最优局部解)
	            else {
	                V[item][weight]=V[item-1][weight];
	            }
	        }
	    }
	    return V[N][W];
	}
}

点赞