<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:
    
    # 2nd SOLUTION => Using Memoization
    # O(nm) time / O(n) space or memory
    # where n is the total amount of numbers and m is the total sum of all different combinations of numbers
    # Time complexity is explained by the fact that for every number we either take it or not (2 possibilities for every number)
    def canPartition(self, nums: List[int]) -> bool:
        # Idea: First sum up all items in the array and check if the final sum if even
        # else return False because in this case there won't be a way to split in 2 parts 
        # with equal sum; Then iterate through the numbers in the array and for each check
        # if we can partition the array at the current position by either taking or
        # not taking the currentitem in the sum
        
        # To optimize time, we use memoization to store the already computed states of the 
        # partition process, so we prevent the program about computing the same state more than once
        
        total_sum = sum(nums)
        if total_sum % 2 == 1: # impossible to split
            return False

        return self.can_partition_here(nums, total_sum, computed_states = {}, index=0, current_sum=0)


    def can_partition_here(self, nums, total_sum, computed_states, index, current_sum):

        current_state = str([index, current_sum])
        if current_state in computed_states:
            return computed_states[current_state]

        if current_sum * 2 == total_sum: # found a valid partition
            return True

        if index >= len(nums) - 1: # checked all items and couldn't find a valid partition
            return False

        found_partition = self.can_partition_here(nums, total_sum, computed_states, index + 1, current_sum + nums[index]) or\
                          self.can_partition_here(nums, total_sum, computed_states, index + 1, current_sum              ) # either take the current item or not take it

        computed_states[current_state] = found_partition

        return computed_states[current_state]


203743