自学内容网 自学内容网

代码随想录算法训练营第三十五天 | 01背包问题 二维 01背包问题 一维 416. 分割等和子集

01背包问题

题目链接:46. 携带研究材料(第六期模拟笔试)

二维动态数组表示:

import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int bagweight = sc.nextInt();
        
        int[] weight = new int[n];
        int[] value = new int[n];
        
        for (int i = 0; i < n; i++) {
            weight[i] = sc.nextInt();
        }
        for (int j = 0; j < n; j++) {
            value[j] = sc.nextInt();
        }
        
        int[][] dp = new int[n][bagweight+1];
        
        //由于后续会用到dp[i-1][j];所以先初始化第一行;
        for(int i = weight[0]; i <= bagweight; i++){
            dp[0][i] = value[0];
        }
        for (int i = 1; i < n; i++) {
            for(int j = 0; j <= bagweight; j++){
                if(j < weight[i]){
                    dp[i][j] = dp[i-1][j];
                }
                else{
                    dp[i][j] = Math.max(dp[i-1][j],dp[i-1][j-weight[i]]+value[i]);
                }
            }
        }
        System.out.println(dp[n-1][bagweight]);
    }
}

一维动态数组表示:

import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int bagweight = sc.nextInt();
        
        int[] weight = new int[n];
        int[] value = new int[n];
        
        for (int i = 0; i < n; i++) {
            weight[i] = sc.nextInt();
        }
        for (int j = 0; j < n; j++) {
            value[j] = sc.nextInt();
        }
        
        int[] dp = new int[bagweight+1];
        
        
        for (int i = 0; i < n; i++) {
            for(int j = bagweight; j >= weight[i]; j--){
                dp[j] = Math.max(dp[j],dp[j-weight[i]]+value[i]);
            }
        }
        System.out.println(dp[bagweight]);
    }
}

 416. 分割等和子集

题目链接:416. 分割等和子集 - 力扣(LeetCode)

思路:若能平分集合,那么其总和必须是偶数,如果和为奇数则直接返回false。剩下我们的目标就是找数字凑够sum/2。等同于背包问题。

class Solution {
    public boolean canPartition(int[] nums) {
        if(nums == null || nums.length == 0) return false;
        int sum = 0;
        for(int num : nums){
            sum += num;
        }
        if(sum % 2 == 1) return false;
        int bagweight = sum / 2;
        
        int n = nums.length;
        int[] dp = new int[bagweight+1];

        for(int i = 0; i < n; i++){
            for(int j = bagweight; j >= nums[i]; j--){
                dp[j] = Math.max(dp[j],dp[j-nums[i]]+nums[i]);
                if(dp[bagweight] == bagweight) return true;
            }

        }
        return dp[bagweight] == bagweight;
        
    }
}


原文地址:https://blog.csdn.net/qq_51792424/article/details/144221921

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!