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:

  1. Each of the array element will not exceed 100.
  2. 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.

题意:

给出一个数组,判断是否可以分成两部分,使得他们的和相等。

思路:

先判断总和是否为偶数,奇数直接pass掉。然后求是否存在一个子数组的和为sum/2,此处利用到背包问题。判断背包是否可以恰好装满。

代码:

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

猜你喜欢

转载自blog.csdn.net/qq_36718317/article/details/80246939