1049.最后一块石头的重量II
https://leetcode.cn/problems/last-stone-weight-ii/
class Solution {
public:
int lastStoneWeightII(vector<int>& stones) {
//尽量让石头分成重量相同的两堆,相撞之后剩下的石头最小,这样就化解成01背包问题了。
int sum = accumulate(stones.begin(), stones.end(), 0);
int m = stones.size();
int n = sum / 2;
vector<int> dp(n + 1, 0);
for (int j = 0; j <= n; j++) {
dp[j] = j >= stones[0] ? stones[0] : 0;
}
for (int i = 1; i < m; i++) {
for (int j = n; j >= 0; j--) {
if (j >= stones[i]) dp[j] = max(dp[j], dp[j - stones[i]] + stones[i]);
}
}
return sum - 2 * dp[n];
}
};
494.目标和
https://leetcode.cn/problems/target-sum/
自己做的:
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int target) {
target = abs(target);
int sum = accumulate(nums.begin(), nums.end(), 0);
if (target > sum) return 0;
vector<vector<int>> dp(nums.size(), vector<int>(sum + 1, 0));
dp[0][nums[0]] = 1;
dp[0][0] *= 2;
for (int i = 1; i < nums.size(); i++) {
for (int j = 0; j <= sum; j++) {
//取+nums[i],寻找abs(j - nums[i])
if (abs(j - nums[i]) <= sum) {
dp[i][j] += dp[i - 1][abs(j - nums[i])];
}
//取-nums[i],寻找j + nums[i]
if (j + nums[i] <= sum) {
dp[i][j] += dp[i - 1][j + nums[i]];
}
}
}
return dp.back()[target];
}
};
使用了卡哥的思路,转换成背包问题
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int target) {
// pos + neg = sum
// pos - neg = tgt
// pos = (sum + tgt) / 2
// neg = (sum - tgt) / 2
int sum = accumulate(nums.begin(), nums.end(), 0);
if ((sum + target) % 2) return 0;
if (abs(target) > sum) return 0;
vector<int> dp ((sum + target) / 2 + 1, 0);
dp[0] = 1;
for (int i = 0; i < nums.size(); i++) {
for (int j = dp.size() - 1; j >= nums[i]; j--) {
dp[j] += dp[j - nums[i]];
}
}
return dp.back();
}
};
474.一和零
https://leetcode.cn/problems/ones-and-zeroes/
class Solution {
public:
int findMaxForm(vector<string>& strs, int m, int n) {
vector<vector<int>> dp (m + 1, vector<int>(n + 1, 0));
for (string str : strs) {
int zeroNums = 0;
int oneNums = 0;
for (char c : str) {
if (c == '0') zeroNums++;
else oneNums++;
}
for (int i = m; i >= zeroNums; i--) {
for (int j = n; j >= oneNums; j--) {
dp[i][j] = max(dp[i][j], dp[i - zeroNums][j - oneNums] + 1);
}
}
}
return dp[m][n];
}
};