代码随想录day36 1049. 最后一块石头的重量 II 494. 目标和 474.一和零
1049. 最后一块石头的重量 II
代码随想录
class Solution {
public:int lastStoneWeightII(vector<int>& stones) {int sum = 0;for (auto & ele : stones) {sum += ele;}int target = sum / 2;vector<int> dp(target + 1, 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 sum - 2 * dp[target];}
};
494. 目标和
代码随想录
class Solution {
public:int findTargetSumWays(vector<int>& nums, int target) {int sum = 0;for (auto & i : nums) {sum += i;}int diff = sum - target;if (diff < 0 || diff % 2 == 1) {return 0;}target = diff / 2;int n = nums.size();vector<vector<int>> dp(n + 1,vector<int>(target + 1, 0));// for (int i = 0; i <= n; i++) {// dp[i][0] = 1;// }dp[0][0] = 1;for (int i = 1; i <= n; i++) {int num = nums[i - 1];for (int j = 0; j <= target; j++) {if (num > j) {dp[i][j] = dp[i - 1][j];} else {dp[i][j] = dp[i - 1][j] + dp[i - 1][j - num];}}}return dp[n][target];}
};
474. 一和零
代码随想录
class Solution {
public:int findMaxForm(vector<string>& strs, int m, int n) {vector<vector<int>> dp(m + 1, vector<int> (n + 1, 0)); // 默认初始化0for (string str : strs) { // 遍历物品int oneNum = 0, zeroNum = 0;for (char c : str) {if (c == '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];}
};