416. Partition Equal Subset Sum

Partition Equal Subset Sum

题目描述:

Given a non-empty array nums 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.

Example 1:

Input: nums = [1,5,11,5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:

Input: nums = [1,2,3,5]
Output: false
Explanation: The array cannot be partitioned into equal sum subsets.

Constraints:

1 <= nums.length <= 200
1 <= nums[i] <= 100
通过次数208,856提交次数407,742

思路:

动态规划题,把题目转化成01背包问题是关键,只有数字组合能达到sum的一半就算true

代码:

func canPartition(nums []int) bool {
    sum := 0
    n := len(nums)
    
    for i:=0;i<n;i++{
        sum += nums[i]
    }
    if sum % 2 == 1{
        return false
    }
    sum /= 2
    dp  := make([]int, sum+1)
    dp[0] = 1
    for i:=0;i<n;i++{
        num := nums[i]
        for j:=sum;j >= num;j--{
            dp[j] |= dp[j - num]
        }
    }
    if dp[sum] == 1{
        return true
    }
    return  false
}

代码效率:

执行用时:8 ms, 在所有 Go 提交中击败了99.43%的用户
内存消耗:3.2 MB, 在所有 Go 提交中击败了70.96%的用户