算法训练营笔记day43|1049. 最后一块石头的重量 II、494. 目标和、

1049. 最后一块石头的重量 II

题目连接

笔记

class Solution {
public:
    int lastStoneWeightII(vector<int>& stones) {
        int sum = 0;
        for (int i : stones) {
            sum += i;
        }
        int len = sum / 2;
        vector<int> dp(len + 1, 0);
        for (int i = 0; i < stones.size(); i++) {
            for (int j = len; j >= 0; j--) {
                if (stones[i] <= j) {
                    dp[j] = max(dp[j], dp[j - stones[i]] + stones[i]);
                }
            }
        }
        return sum - 2 * dp[len];
    }
};

494. 目标和

题目连接

笔记

class Solution {
public:
    int findTargetSumWays(vector<int>& nums, int target) {
        int sum = 0;
        for (int i : nums) {
            sum += i;
        }
        if ((sum + target) % 2 == 1) return 0;
        if (abs(target) > sum) return 0;
        int bagSize = (sum + 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] + dp[j - nums[i]];
            }
        }
        return dp[bagSize];
    }
};

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 (char c : strs[i]) {
                if (c == '0') zeroNum++;
                else oneNum++;
            }
            for (int j = m; j >= zeroNum; j--) {
                for (int k = n; k >= oneNum; k--) {
                    dp[j][k] = max(dp[j][k], dp[j - zeroNum][k - oneNum] + 1);
                }
            }
        }
        return dp[m][n];
    }
};

你可能感兴趣的:(算法,笔记,leetcode)