1049. 最后一块石头的重量 II
分成两堆,一起碰撞,两堆相减
class Solution {
public:
// 分成两堆,尽可能满 sum/2
int lastStoneWeightII(vector<int>& stones) {
int n = stones.size();
int sum = 0;
for (const int& stone : stones)
sum += stone;
int sum2 = sum;
sum /= 2;
// 尽可能满sum
vector<int> dp(sum + 1);
for (int i = stones[0]; i <= sum; i ++)
dp[i] = stones[0];
for (int i = 1; i < n; i ++)
{
for (int j = sum; j >= 0; j --)
if (j >= stones[i])
dp[j] = max(dp[j], dp[j-stones[i]] + stones[i]);
}
return sum2 - dp[sum] * 2;
}
};
494. 目标和
带有一点点的推公式,写在注释里了。
class Solution {
public:
// 正数之和是x 负数之和是sum - x
// 2*x - sum == target => x = (sum + target) / 2
// dp 次数相关
int findTargetSumWays(vector<int>& nums, int target) {
int sum = 0;
int n = nums.size();
for (const int& num : nums)
sum += num;
if (abs(target) > sum) return 0; // 无法达到
sum += target;
if (sum & 1) return 0;
sum /= 2; // 最后要达到的和
vector<int> dp(sum + 1);
dp[0] = 1;
for (int i = 0; i < n; i ++) //空也算一种,[0] 0 => 结果是2
{
for (int j = sum; j >= 0; j --)
{
if (nums[i] <= j)
dp[j] += dp[j - nums[i]];
}
}
return dp[sum];
}
};
474. 一和零
二维优化成一位,这个是三维优化成二维。
class Solution {
public:
int findMaxForm(vector<string>& strs, int m, int n) {
vector<vector<int>> dp(m + 1, vector<int> (n + 1));
for (const string& str : strs)
{
int zeroNum = 0, oneNum = 0;
for (auto ch : str)
{
if (ch == '0') zeroNum ++;
else oneNum ++;
}
for (int i = m; i >= zeroNum; i --)
{
for (int j = n; j >= oneNum; j --)
{
dp[i][j] = max(dp[i][j], dp[i - zeroNum][j - oneNum] + 1);
}
}
}
return dp[m][n];
}
};