website/content.en/ChapterFour/0400~0499/0416.Partition-Equal-Subset-Sum.md
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:
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.
Given a non-empty array containing only positive integers. Determine whether this array can be partitioned into two subsets such that the sum of the elements in both subsets is equal.
Note:
F(n,C) represents filling a knapsack of capacity C with n items, and the state transition equation is F(i,C) = F(i - 1,C) || F(i - 1, C - w[i]). If i - 1 items can already fill C, this case satisfies the requirement. At the same time, if i - 1 items cannot fill the knapsack, but after adding the i-th item it can exactly fill the knapsack, this also satisfies the requirement. The time complexity is O( n * sum/2 ) = O( n * sum).
package leetcode
func canPartition(nums []int) bool {
sum := 0
for _, v := range nums {
sum += v
}
if sum%2 != 0 {
return false
}
// C = half sum
n, C, dp := len(nums), sum/2, make([]bool, sum/2+1)
for i := 0; i <= C; i++ {
dp[i] = (nums[0] == i)
}
for i := 1; i < n; i++ {
for j := C; j >= nums[i]; j-- {
dp[j] = dp[j] || dp[j-nums[i]]
}
}
return dp[C]
}