【代码随想录Day42】动态规划

1049 最后一块石头的重量 II

https://leetcode.cn/problems/last-stone-weight-ii/

选一堆石头使得他们的和尽量最大但不超过 sum/2。

class Solution { //其实就是尽量让石头分成重量相同的两堆,相撞之后剩下的石头最小
    public int lastStoneWeightII(int[] stones) {
        int sum = 0;
        for (int stone : stones) {
            sum += stone;
        }
        int[] dp = new int[sum / 2 + 1];
        for (int i = 0; i < stones.length; i++) {
            for (int j = sum / 2; j >= stones[i]; j--) { // 注意j >= stones[i]
                dp[j] = Math.max(dp[j], dp[j - stones[i]] + stones[i]);
            }
        }
        return sum - 2 * dp[sum / 2];
    }
}

494 目标和

https://leetcode.cn/problems/target-sum/

选出一组数使他们前面填减号,他们的和为(sum - target) / 2,由于是找num of ways,初始值为0个数里和为0的ways = 1,其余都是0.

class Solution {
    public int findTargetSumWays(int[] nums, int target) {
        int sum = 0;
        for (int n : nums) sum += n;            //在nums种选一个subset是的其和 * 2 等于(sum - target) 这组前加负号 (sum - neg) - neg = target 
        if (sum < target || (sum - target) % 2 == 1) return 0;
        int neg = (sum - target) / 2;
        int[] dp = new int[neg + 1];         //用前i个数中选出和为j的方案数  
        dp[0] = 1;
        for (int i = 1; i <= nums.length; i++) {
            for (int j = neg; j >= nums[i - 1]; j--) {
                   dp[j] += dp[j - nums[i - 1]];
            }
        }
        return dp[neg];
    }
}

474一和零

https://leetcode.cn/problems/ones-and-zeroes/

dp[i][j]表示i个0和j个1时的最大子集个数

class Solution {
    public int findMaxForm(String[] strs, int m, int n) {
        int[][] dp = new int[m + 1][n + 1];          //dp[i][j]表示i个0和j个1时的最大子集
        for (int i = 0; i < strs.length; i++) {
            int countOne = 0, countZero = 0;
            for (int l = 0; l < strs[i].length(); l++) {
                if (strs[i].charAt(l) == '1') {
                    countOne++;
                } else {
                    countZero++;
                }
            }
            for(int j = m; j >= countZero; j--) {
                for (int k = n; k >= countOne; k--) {
                    dp[j][k] = Math.max(dp[j][k], dp[j - countZero][k - countOne] + 1);
                }
            }
        }
        return dp[m][n];
    }
}

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