01背包问题
public class Test02 {
public static void main(String[] args) {
int[]value=new int[]{15,20,30};
int[]weight=new int[]{1,3,4};
int packageSize=4;
Test02 test02 = new Test02();
test02.testPageageProblem(value,weight,packageSize);
}
public int testPageageProblem(int[]value,int[]weight,int packageSize){
int[]dp=new int[packageSize+1];
for(int i=0;i<value.length;i++){
for(int j=packageSize;j>=weight[i];j--){
dp[j]=Math.max(dp[j],value[i]+dp[i-weight[i]]);
}
}
return dp[packageSize];
}
}
416. 分割等和子集
int sum=0;
for (int num : nums) {
sum+=num;
}
int packageSize=0;
if(sum%2==1){
return false;
}else{
packageSize=sum/2;
}
int[]dp=new int[packageSize+1];
for(int i=0;i<nums.length;i++){
for(int j=packageSize;j>=nums[i];j--){
dp[j]=Math.max(dp[j],nums[i]+dp[j-nums[i]]);
}
}
return dp[packageSize]==packageSize;
1049. 最后一块石头的重量 II
int sum=0;
for (int stone : stones) {
sum+=stone;
}
int packageSize=sum/2;
int[]dp=new int[packageSize+1];
for(int i=0;i<stones.length;i++){
for(int j=packageSize;j>=stones[i];j--){
dp[j]=Math.max(dp[j],stones[i]+dp[j-stones[i]]);
}
}
int nowWeight=dp[packageSize];
int rest=sum-nowWeight;
return Math.abs(rest-nowWeight);
494. 目标和
int sum=0;
for (int num : nums) {
sum+=num;
}
sum+=target;
if(sum%2==1||sum<0){
return 0;
}
int packageSize=sum/2;
int[]dp=new int[packageSize+1];
dp[0]=1;
for(int i=0;i<nums.length;i++){
for(int j=packageSize;j>=nums[i];j--){
dp[j]+=dp[j-nums[i]];
}
}
return dp[packageSize];
474. 一和零
int[][]dp=new int[m+1][n+1];
for (String str : strs) {
char[] chars = str.toCharArray();
int zeroCount=0;
int oneCount=0;
for(int i=0;i<chars.length;i++){
if(chars[i]=='1'){
oneCount++;
}else{
zeroCount++;
}
}
for(int i=m;i>=zeroCount;i--){
for(int j=n;j>=oneCount;j--){
dp[i][j]=Math.max(dp[i][j],dp[i-zeroCount][j-oneCount]+1);
}
}
}
return dp[m][n];