1049. 最后一块石头的重量 II
尽量让石头分成重量相同的两堆,相撞之后剩下的石头最小,这样就化解成01背包问题了。
class Solution {
public:
int lastStoneWeightII(vector<int>& stones) {
int s = 0;
for(int n: stones) s += n;
int target = s / 2;
vector<int> dp(1501, 0);
for(int i = 0; i < stones.size(); i++){
for(int j = target; j >= stones[i]; j--){
dp[j] = max(dp[j], dp[j - stones[i]] + stones[i]);
}
}
return s - dp[target] - dp[target];
}
};
494. 目标和
https://leetcode.cn/problems/target-sum/
假设加法的总和为x,那么减法对应的总和就是sum - x。
所以我们要求的是 x - (sum - x) = target
x = (target + sum) / 2
此时问题就转化为,装满容量为x的背包,有几种方法。
dp[j] 表示:填满j(包括j)这么大容积的包,有dp[j]种方法
在求装满背包有几种方法的情况下,递推公式一般为:dp[j] += dp[j - nums[i]]
从递推公式可以看出,在初始化的时候dp[0] 一定要初始化为1,因为dp[0]是在公式中一切递推结果的起源,如果dp[0]是0的话,递推结果将都是0。
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int target) {
int s = 0;
for(int n: nums) s += n;
if((s + target) % 2 == 1) return false;
if(abs(target) > s) return false;
int bagSize = (s + target) / 2;
vector<int> dp(bagSize + 1, 0);
dp[0] = 1;
for(int i = 0; i < nums.size(); i++){
for(int j = bagSize; j >= nums[i]; j--){
dp[j] += dp[j - nums[i]];
}
}
return dp[bagSize];
}
};
474.一和零
https://leetcode.cn/problems/ones-and-zeroes/
本题中strs 数组里的元素就是物品,每个物品都是一个!而m 和 n相当于是一个背包,两个维度的背包。本题其实是01背包问题!只不过这个背包有两个维度,一个是m 一个是n,而不同长度的字符串就是不同大小的待装物品。
dp[i][j]:最多有i个0和j个1的strs的最大子集的大小为dp[i][j]。
递推公式:dp[i][j] = max(dp[i][j], dp[i - zeroNum][j - oneNum] + 1);
class Solution {
public:
int findMaxForm(vector<string>& strs, int m, int n) {
vector<vector<int>> dp(m + 1, vector<int> (n + 1, 0));
for(auto str: strs){
int one = 0, zero = 0;
for(auto c: str){
if(c == '1') one++;
else zero++;
}
for(int i = m; i >= zero; i--){
for(int j = n; j >= one; j--){
dp[i][j] = max(dp[i][j], dp[i - zero][j - one] + 1);
}
}
}
return dp[m][n];
}
};
0-1背包的多种应用,
- 纯 0 - 1 背包 (opens new window)是求 给定背包容量 装满背包 的最大价值是多少。
-
- 分割等和子集 (opens new window)是求 给定背包容量,能不能装满这个背包。
-
- 最后一块石头的重量 II (opens new window)是求 给定背包容量,尽可能装,最多能装多少
-
- 目标和 (opens new window)是求 给定背包容量,装满背包有多少种方法。
- 本题是求 给定背包容量,装满背包最多有多少个物品。