dp4

  1. 最后一块石头的重量 II
class Solution {
public:
    int lastStoneWeightII(vector<int>& stones) {
        int n = stones.size();
        int s = reduce(stones.begin(), stones.end());
        int t = s / 2;
        vector<vector<int>> dp(n + 1, vector<int>(t + 1));
        dp[0][0] = 0;
        for(int i = 0; i < n; i++)
        {
            int x = stones[i];
            for(int j = 0; j <= t; j++)
            {
                dp[i + 1][j] = dp[i][j];
                if(j >= stones[i])
                    dp[i + 1][j] = max(dp[i + 1][j], dp[i][j - x] + x);
            }
        }
        
        return s - dp[n][t] - dp[n][t];
    }
};
  1. 目标和
class Solution {
public:
    int findTargetSumWays(vector<int>& nums, int target) {
        int n = nums.size();
        target += reduce(nums.begin(), nums.end());
        if(target < 0|| target % 2)
            return 0;
        target = target / 2;
        vector<vector<int>> dp(n+1, vector<int>(target + 1));
        dp[0][0] = 1;
        for(int i = 0; i < n; i++)
        {
            int x = nums[i];
            for(int j = 0; j <= target; j++)
            {
                if(j >= x)
                    dp[i + 1][j] = dp[i][j] + dp[i][j - x];
                else
                    dp[i + 1][j] = dp[i][j];
            }
        }
        return dp[n][target];
    }
};
  1. 一和零
class Solution {
public:
    int findMaxForm(vector<string>& strs, int m, int n) {
        vector<vector<int>> dp(m + 2, vector<int>(n + 2, 0));
        for(string &str: strs)
        {
            int x = 0, y = 0;
            for(char &c: str)
            {
                if(c == '0')
                    x++;
                if(c == '1')
                    y++;
            }
            for(int i = m; i >= x; i--)
            {
                for(int j = n; j >= y; j--)
                    dp[i][j] = max(dp[i - x][j - y] + 1, dp[i][j]);
            }
        }
        return dp[m][n];
    }
};
posted @ 2025-02-22 16:47  skyler886  阅读(13)  评论(0)    收藏  举报