# 【背包+DP】背包问题+面试实例

N件物品，每件重量为weight[i]，价值为price[i]，问如何装进容易Vol的背包中得到背包价值最大。

0-1背包：每件物品只有一个；

0-1背包：

DP： dp[i][j] 表示j的背包中装进前i件物品所得到的最大价值。

static int zeroOnePack(int [] weight, int [] price, int vol){

int [] record = new int [vol + 1];

for(int i = 0; i < weight.length; ++i){
for(int k = vol; k >= weight[i]; --k){
if(record[k] < record[k - weight[i]] + price[i])
record[k] = record[k - weight[i]] + price[i];
}
}
return record[vol];
}

static int fullPack(int [] weight, int [] price, int vol){

int [] record = new int [vol + 1];

for(int i = 0; i < weight.length; ++i){
for(int k = weight[i]; k <= vol; ++k){
if(record[k] < record[k - weight[i]] + price[i])
record[k] = record[k - weight[i]] + price[i];
}
}
return record[vol];
}

===================================================================

a=[1,4,5,6],子集[1,5]和[6]满足条件，返回6。

import java.util.Arrays;

public class equalSubSet {
static int maxSum = 1000;
static boolean [][] dp = new boolean [maxSum][maxSum];

public static void main(String[] args) {
dp[0][0] = true;
int [] nums = {1,2,2,2,3,4,6};
for(int i = 0; i < nums.length; ++i){
equalSubset(nums[i]);
}
for(int i = maxSum - 1; i >= 0; --i){
if(dp[i][i]){
System.out.println(i);
break;
}
}
}

static void equalSubset(int num){

for(int i = maxSum - 1; i >= 0; --i){
for(int k = maxSum - 1; k >= 0; --k){
if(k >= num && dp[i][k - num])
dp[i][k] = true;
if(i >= num && dp[i - num][k])
dp[i][k] = true;
}
}
}
}