代码随想录Day43 | 1049. 最后一块石头的重量 II 、 494. 目标和 、474.一和零

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

dp含义:容量为j的背包,最多可以背最大重量为dp[i]

递推公式:dp[j] = max(dp[j], dp[j - stones[i]] + stones[i])

初始化:dp[j]=0

遍历顺序:先物品后背包,先顺序后倒序

class Solution {
public:
    int lastStoneWeightII(vector& stones) {
        vector dp(15001, 0);
        int sum = 0;
        for (int i = 0; i < stones.size(); i++) sum += stones[i];
        int target = sum / 2;
        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 - dp[target] - dp[target];
    }
};

494. 目标和

定义前面为加号的是left数组,前面为减号的为right数组

left+right=sum

left-right=target

left=(sum+target)/2

dp含义:装满容量为j的背包有dp[j]种方法

递推公式:dp[j]+=dp[j-nums[i]]

初始化:dp[0]=1

遍历顺序:先物品后背包,先顺序后倒序

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

474.一和零 

dp含义:最多有i个0和j个1的最大子集大小为dp[i][j]

递推公式:dp[i][j] = max(dp[i][j], dp[i - zeroNum][j - oneNum] + 1)

初始化:dp[0][0]=0

遍历顺序:都行

class Solution {
public:
    int findMaxForm(vector& strs, int m, int n) {
        vector> dp(m + 1, vector (n + 1, 0)); 
        for (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];
    }
};

你可能感兴趣的:(算法,动态规划)