416. Partition-Equal-Subset-Sum

Question Link

Difficulty: Medium

Another day, another dynamic programming problem, I would rather e-

Anyways, there’s a very easy initial check to do: We can check if the sum of the entire array is even or odd. If it is odd, we already know that we cannot partition the array into two equal subsets and we can return False early.

Now that we know that the sum is even, we can also easily calculate what each subset should sum up to (total // 2). This is a very simple dynamic programming program (although I initially thought that this would result in the dp array being too large).

The basic idea is that for each number, we have two choices:

So inside dp[i], we can store whether or not we can reach the sum i using the numbers in the array.

So the recurrence relation is:

Then we can just return dp[bag] to check if we can reach the target sum.

class Solution(object):
    def canPartition(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        n = len(nums)
        total = sum(nums)
        
        if total % 2 == 1:
            return False

        bag = total // 2
        dp = [False] * (bag + 1)
        dp[0] = True

        for num in nums:
            for curr in range(bag, num - 1, -1):
                dp[curr] = dp[curr] or dp[curr - num]
        
        return dp[bag]

Time Complexity: O(n * bag)

Space Complexity: O(bag)

Time Taken: too long