题解 | #分割等和子集#

分割等和子集

http://www.nowcoder.com/practice/65ade309fa4d4067a9add749721bfdc0

01背包问题,需要注意是奇数就直接返回,返回dp[sum / 2] == sum / 2;

import java.util.Scanner;

/**
 * @program: springDemo
 * @author: JiaLe Hu
 * @create: 2022-03-18 17:43
 **/

public class Main {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        int n = reader.nextInt();
        int[] nums = new int[n + 1];
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            nums[i] = reader.nextInt();
            sum += nums[i];
        }
        if (sum % 2 != 0) {
            System.out.println(false);
            return ;
        }
        
        int[] dp = new int[sum + 1];
        dp[0] = 0;
        for (int i = 1; i <= sum; i++) {
            for (int j = 1; j <= n; j++) {
                if (i >= nums[j]) {
                    dp[i] = Math.max(dp[i - nums[j]] + nums[j], dp[i]);
                }
            }
        }
        System.out.println(dp[sum / 2] == sum / 2);
    }
}
全部评论

相关推荐

已老实求offer😫:有点像徐坤(没有冒犯的意思哈)
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务