LeetCode—416. Partition Equal Subset Sum—Analysis and Code (Java)

LeetCode—416. Partition Equal Subset Sum [Partition Equal Subset Sum]—Analysis and Code [Java]

1. Title

Given a contains only positive integer is non-empty array. Is it possible to divide this array into two subsets so that the sum of the elements of the two subsets is equal.

note:

The elements in each array will not exceed 100 and
the size of the array will not exceed 200

Example 1:

输入: [1, 5, 11, 5]
输出: true
解释: 数组可以分割成 [1, 5, 5] 和 [11].

Example 2:

输入: [1, 2, 3, 5]
输出: false
解释: 数组不能分割成两个元素和相等的子集.

Source: LeetCode
Link: https://leetcode-cn.com/problems/partition-equal-subset-sum The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, analysis and code

1. Dynamic programming

(1) Thinking

The array can be divided into two elements and equal subsets, which is equivalent to the existence of some elements in the array, and the sum is half of the sum of the array elements. Therefore, this problem can be converted into a knapsack problem and solved by dynamic programming.

(2) Code

class Solution {
    
    
    public boolean canPartition(int[] nums) {
    
    
        if (nums.length == 0)
            return false;
        
        int sum = 0;
        for (int i = 0; i < nums.length; i++)
            sum += nums[i];
        if ((sum & 1) == 1)
            return false;
        sum >>= 1;
        
        boolean[] hasSum = new boolean[sum + 1];
        hasSum[0] = true;
        for (int i = 1; i < sum + 1; i++)
            hasSum[i] = false;
        for (int i = 0; i < nums.length; i++) {
    
    
            for (int j = sum; j >= 0; j--) {
    
    
                if (j + nums[i] < sum + 1 && hasSum[j] == true) {
    
    
                    if (j + nums[i] == sum)
                        return true;
                    hasSum[j + nums[i]] = true;
                }
            }
        }

        return hasSum[sum];
    }
}

(3) Results

Execution time: 11 ms, beating 91.54% of users
in all Java submissions ; memory consumption: 38 MB, beating 78.48% of users in all Java submissions.

Three, other

Nothing.

Guess you like

Origin blog.csdn.net/zml66666/article/details/103431360