1049. 最后一块石头的重量 II
题目:力扣
class Solution {
public:
int lastStoneWeightII(vector<int>& stones) {
int sum = 0;
for(int i = 0; i < stones.size(); ++i){
sum += stones[i];
}
int fin = sum / 2;
vector<int> dp(fin+1,0);
for(int i = 0;i < stones.size(); ++i){
for(int j = fin; j >= stones[i]; --j){
dp[j] = max(dp[j],dp[j-stones[i]] + stones[i]);
}
}
int ans = sum - 2 * dp[fin] ;
return ans;
}
};
494. 目标和
题目:力扣
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int target) {
int sum = 0;
for(int a : nums){
sum += a;
}
int s = (sum + target) / 2;
if((sum + target) % 2 == 1) return 0;
if(abs(s) > sum) return 0;
if(s < 0) return 0;
vector<int> dp(s+1,0);
dp[0] = 1;
for(int i = 0; i < nums.size(); ++i){
for(int j = s; j >= nums[i]; --j){
dp[j] += dp[j - nums[i]];
}
}
return dp[s];
}
};
474.一和零
题目:力扣
class Solution {
public:
int findMaxForm(vector<string>& strs, int m, int n) {
vector<vector<int> > dp(m+1,vector<int>(n+1,0));
for(int i = 0; i < strs.size(); ++i){
int zeroNum = 0;
int oneNum = 0;
for(int j = 0; j < strs[i].size(); ++j){
if(strs[i][j] == '0') zeroNum++;
if(strs[i][j] == '1') oneNum++;
}
for(int k = m; k >= zeroNum; --k){
for(int l = n; l >= oneNum; --l){
dp[k][l] = max(dp[k][l], dp[k-zeroNum][l -oneNum] + 1);
}
}
}
return dp[m][n];
}
};
总结
题型:0/1背包解决组合问题