<p>Given an integer array <code>nums</code>, return <code>true</code> <em>if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or </em><code>false</code><em> otherwise</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,5,11,5]
<strong>Output:</strong> true
<strong>Explanation:</strong> The array can be partitioned as [1, 5, 5] and [11].
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,2,3,5]
<strong>Output:</strong> false
<strong>Explanation:</strong> The array cannot be partitioned into equal sum subsets.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 200</code></li>
	<li><code>1 &lt;= nums[i] &lt;= 100</code></li>
</ul>

class Solution:
    def canPartition(self, nums: List[int]) -> bool:
        '''
        need a sub group that sums to 1/2 of total sum
        make total sum. if odd, return False

        Backtracking problem that sums to total_sum/2
        dfs(partial_sum, index):
            if partial_sum:
                return True
            if index >= len(nums):
                return False
            res = False
            for i in range(index, len(nums)):
                n = nums[i]
                # with
                res = res or dfs(partial_sum + n, index+1)

                # without
                res = res or dfs(partial_sum, index+1)
            
            return res
        '''
        total_sum = sum(nums)
        if total_sum % 2 == 1:
            return False
        half_sum = total_sum /2

        cache = {}
        

        def dfs(partial_sum, index):
            key = str(partial_sum) + '/' + str(index)
            if key in cache:
                return cache[key]
            if index >= len(nums) or partial_sum > half_sum:
                cache[key] = False
                return False
            # print(partial_sum, index, stack)
            if partial_sum == half_sum:
                cache[key] = True
                return True
            res = False

            n = nums[index]

            # without
            res = res or dfs(partial_sum, index+1)
            
            # with
            res = res or dfs(partial_sum+n, index+1)
            
            cache[key] = res
            return res

        return dfs(0,0)
251373