DevPath

← All problems

Partition Equal Subset Sum

Medium dynamic-programming

Description

Return true if the array can be split into two subsets with equal sum.

Constraints

1 <= n <= 200; positive values

Examples

Input: nums = [1,5,11,5]

Output: true

Hints (1)
  • Total must be even; then check whether a subset of half the total exists.

Solutions

Subset-sum to half. · Time O(n*target) · Space O(target)

func canPartition(nums []int) bool {
    total := 0
    for _, n := range nums {
        total += n
    }
    if total%2 != 0 {
        return false
    }
    target := total / 2
    dp := make([]bool, target+1)
    dp[0] = true
    for _, n := range nums {
        for s := target; s >= n; s-- {
            if dp[s-n] {
                dp[s] = true
            }
        }
    }
    return dp[target]
}

Create a free account to submit solutions, track progress and save problems.

Create account