Java | LeetCode | 416. Partition Equal Subset Sum | 背包问题 | 动态规划

416. Partition Equal Subset Sum | 背包问题 | 动态规划

问题描述

Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.

Note:

Each of the array element will not exceed 100.
The array size will not exceed 200.

Example 1:

Input: [1, 5, 11, 5]

Output: true

Explanation: The array can be partitioned as [1, 5, 5] and [11].

Example 2:

Input: [1, 2, 3, 5]

Output: false

Explanation: The array cannot be partitioned into equal sum subsets.

思路

本题要找是否给定的正数数组是否能被分成两部分,使两部分的和相等。也就是说,需要从物品(数组)中,找到价值(和)为数组总和的一半的物品,放进背包。

如果能够找到,返回true,否则false。

代码

class Solution {
    public boolean canPartition(int[] nums) {
    	// 数组求和
        int sum = 0;
        for(int num : nums) sum += num;
        // 如果和是奇数,说明价值不可能正好为和的一半,结果为false
        if(sum%2!=0) return false;
        int[] dp = new int[sum];
        return canPartition(nums, 0, sum/2, 0, dp);
    }
    public boolean canPartition(int[] nums, int sum, int target, int i, int[] dp) {
    	// 当前和为目标
        if(sum==target) return true;
        // i超过界限或者和比目标大
        if(i>=nums.length || sum>target) return false;
        // 之前储存了结果,不再计算一遍,直接返回
        // 用 int[] dp 而不用 boolean[] dp 是为了区分已计算的和未计算的
        if(dp[sum]!=0) return dp[sum]==1 ? true : false;
        boolean res = canPartition(nums, sum+nums[i], target, i+1, dp) || canPartition(nums, sum, target, i+1, dp);
        // 当前结果存到dp中
        dp[sum] = res ? 1 : -1;
        return res;
    }
}

Beats 100%

在这里插入图片描述
在这里插入图片描述