代码随想录算法训练营第四十三天| LeetCode1049. 最后一块石头的重量 II 494. 目标和 474.一和零

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

题目:力扣

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

        }
        int ans = sum - 2 * dp[fin] ;
        return ans;
    }
};

494. 目标和

题目:力扣

class Solution {
public:
    int findTargetSumWays(vector& nums, int target) {
        int sum = 0;
        for(int a : nums){
            sum += a;
        }
        int s = (sum + target) / 2;
        if((sum + target) % 2 == 1) return 0;
        if(abs(s) > sum) return 0;
        if(s < 0) return 0;
        vector dp(s+1,0);
        dp[0] = 1;
        for(int i = 0; i < nums.size(); ++i){
            for(int j = s; j >= nums[i]; --j){
                dp[j] += dp[j - nums[i]];
            }
        }
        return dp[s];
    }
};

474.一和零

题目:力扣

class Solution {
public:
    int findMaxForm(vector& strs, int m, int n) {
        vector > dp(m+1,vector(n+1,0));
        for(int i = 0; i < strs.size(); ++i){
            int zeroNum = 0;
            int oneNum = 0;
            for(int j = 0; j < strs[i].size(); ++j){
                if(strs[i][j] == '0') zeroNum++;
                if(strs[i][j] == '1') oneNum++;
            }
            for(int k = m; k >= zeroNum; --k){
                for(int l = n; l >= oneNum; --l){
                    dp[k][l] = max(dp[k][l], dp[k-zeroNum][l -oneNum] + 1);
                }
            }
        }
        return dp[m][n];
    }
};

总结

题型:0/1背包解决组合问题

你可能感兴趣的:(代码随想录算法训练营,leetcode,算法,动态规划)