Day 36 of LeetCode

ยท

1 min read

Documenting LeetCode solving.

Q105

416. Partition Equal Subset Sum

Medium.

class Solution:
    def canPartition(self, nums: List[int]) -> bool:
        if sum(nums) % 2:
            return False

        dp = set()
        # make sure dp set is not empty at first iteration
        dp.add(0)
        # two subsets must equal to half of the total sum
        target = sum(nums) // 2

        for i in range(len(nums) - 1, -1, -1):
            nextDP = set()
            for t in dp:
                nextDP.add(t + nums[i])
                nextDP.add(t)
            dp = nextDP

        return True if target in dp else False
ย