【代码随想录训练营】【Day42】第九章|动态规划|01背包问题(二维)|01背包问题(一维|滚动数组)|416.分割等和子集

01背包 — 理论基础(二维)

详细的题解可以查阅:《代码随想录》 — 01背包理论基础

Java解法(动态规划):

class Question{
	public int solve(int bagWeight, int[] weights, int[] values){
		int[][] dp = new int[weights.length][bagWeight + 1];
		for(int j = weights[0]; j <= bagWeight; j++){
			dp[0][j] = values[0];
		}
		for(int i = 1; i < values.length; i++){
			for(int j = 0; j <= bagWeight; j++){
				dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weights[i]] + values[i]);
			}
		}
		return dp[weights.length - 1][bagWeight];
	}

	public static void main(String[] args){
		int[] weights = new int[]{1, 3, 4};
		int[] values = new int[]{15, 20, 30};
		int bagWeight = 4;
		return solve(bagWeight, weights, values);
}

01背包 — 理论基础(一维|滚动数组|重点掌握)

详细的题解可以查阅:《代码随想录》 — 01背包-2理论基础

Java解法(动态规划):

class Question{
	public int solve(int bagWeight, int[] weights, int[] values){
		int[] dp = new int[bagWeight + 1];
		for(int i = 0; i < weights.length; i++){
			// 一维dp遍历的时候,背包是从大到小遍历
			for(int j = bagWeight; j >= weights[i]; j--){
				dp[j] = Math.max(dp[j], dp[j - weights[i]] + values[i]);
			}
		}
		return dp[bagWeight];
	}

	public static void main(String[] args){
		int[] weights = new int[]{1, 3, 4};
		int[] values = new int[]{15, 20, 30};
		int bagWeight = 4;
		return solve(bagWeight, weights, values);
}

分割等和子集(01背包的应用题)

题目详细:LeetCode.416

详细的题解可以查阅:《代码随想录》 — 分割等和子集

Java解法(动态规划):

class Solution {
    public boolean canPartition(int[] nums) {
        int[] dp = new int[100*100+1];
        int sum = Arrays.stream(nums).sum(), target = sum / 2;
        if(sum % 2 == 1) return false;
        for(int i = 0; i < nums.length; i++){
            for(int j = target; j >= nums[i]; j--){
                dp[j] = Math.max(dp[j], dp[j - nums[i]] + nums[i]);
            }
        }
        return target == dp[target];
    }
}

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