Formatted question description: https://leetcode.ca/all/416.html

# 416. Partition Equal Subset Sum

Medium

## Description

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 .


Example 2:

Input: [1, 2, 3, 5]

Output: false

Explanation: The array cannot be partitioned into equal sum subsets.


## Solution

First calculate the sum of the numbers in the array nums. If the sum is odd, then it is impossible to partition the array into two subsets that have equal sum, so return false.

Let length be the length of the array nums and let target be half of the sum of the numbers in the array nums. Use dynamic programming. Create a 2D array dp of type boolean with length rows and target + 1 columns, where dp[i][j] represents whether it is possible to select some numbers from the first i numbers of nums such that they sum up to j, where j ranges from 0 to target. Initialize column 0 for each row to be true since selecting nothing will lead to sum 0. Then initialize dp[nums] = true. For i from 1 to length - 1, let num = nums[i], and for each j from 1 to target, update dp[i][j] as dp[i - 1][j] || dp[i - 1][j - num], where the latter can only be applied when j >= num. If the first i - 1 numbers contain one or more numbers that sum up to j, then when the i-th number is added, the same numbers still sum up to j. If j >= num and the first i - 1 numbers contain one or more numbers that sum up to j - num, then when the i-th number which is num is added, the same numbers still sum up to j - num, and the same numbers with the newly added number num will sum up to j.

Finally, return dp[length - 1][target].

Java

class Solution {
public boolean canPartition(int[] nums) {
int sum = 0;
for (int num : nums)
sum += num;
if (sum % 2 != 0)
return false;
int length = nums.length;
if (length < 2)
return false;
int target = sum / 2;
if (nums[length - 1] > target)
return false;
else if (nums[length - 1] == target)
return true;
boolean[][] dp = new boolean[length][target + 1];
for (int i = 0; i < length; i++)
dp[i] = true;
dp[nums] = true;
for (int i = 1; i < length; i++) {
int num = nums[i];
for (int j = 1; j <= target; j++) {
if (j >= num)
dp[i][j] = dp[i - 1][j] || dp[i - 1][j - num];
else
dp[i][j] = dp[i - 1][j];
}
}
return dp[length - 1][target];
}
}