<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 {
public:

    struct Cache{
        std::vector<std::optional<int>> values;
        int width;
    };

    int getId(int lastElement, int maxValue, const Cache &cache){
        return maxValue + cache.width * lastElement;
    }

    int getMaxImpl(int lastElement, int maxValue, const std::vector<int> &nums, Cache &cache){
        int currentIndex = getId(lastElement, maxValue, cache);
        if(cache.values[currentIndex].has_value())
            return cache.values[currentIndex].value();

        auto ret = [&](){
            if(nums[lastElement] > maxValue){
                if(lastElement == 0)
                    return 0;
                return getMaxImpl(lastElement - 1, maxValue, nums, cache);
            }

            if(lastElement == 0)
                return nums[lastElement];

            return std::max(nums[lastElement] + getMaxImpl(lastElement - 1, maxValue - nums[lastElement], nums, cache), 
                            getMaxImpl(lastElement - 1, maxValue, nums, cache));
        }();

        cache.values[currentIndex] = ret;
        return ret;
    }

    bool canPartition(vector<int>& nums) {
        
        auto sum = std::accumulate(nums.begin(), nums.end(), 0);
        if(sum % 2)
            return false;
        auto objective = sum / 2;

        Cache cache;
        cache.values = std::vector<std::optional<int>>(nums.size() * (objective + 1), std::nullopt);
        cache.width = (objective + 1);
        
        return getMaxImpl(nums.size() - 1, objective, nums, cache) == objective;
    }
};
165310