Problem: MLE
I am confused as to why the LeetCode judge reports Memory Limit Exceeded when my solution looks close to the editorial solution. I not too familiar with @lru_cache
and was using a memo dictionary at first that would take a tuple of index, and the sum of the subset. I change my code to see if that would make a difference, and it did not. With this being said, I am not just having a problem with memory, I am also having a problem with runtime. This is leading me to believe that there's a problem with the algorithm itself. Understanding why I am having these complications would be greatly appreciated as I am in the early stages of learning backtracking + memo / dynamic programing.
Mentions -> The find
method is the one I created, while dfs
is the LeetCode editorial for top-down approach. Also, feel free to comment on the structure or any opinions.
Link: https://leetcode.com/problems/partition-equal-subset-sum/?envType=daily-question&envId=2025-04-07
Problem Statement:
Given an integer array
nums
, returntrue
if you can partition the array into two subsets such that the sum of the elements in both subsets is equal orfalse
otherwise.
class Solution:
def canPartition(self, nums: List[int]) -> bool:
equal = sum(nums)
if equal & 1 == 1:
return False
equal //= 2
@lru_cache(maxsize=None)
def find(place, sum_):
if place >= len(nums) or sum_ > equal :
return False
if sum_ == equal:
return True
temp1 = find(place+1,sum_ + nums[place])
temp2 = find(place+1,sum_)
return temp1 | temp2
return find(0,0)
Leetcode Implementation Below
@lru_cache(maxsize=None)
def dfs(nums: Tuple[int], n: int, subset_sum: int) -> bool:
# Base cases
if subset_sum == 0:
return True
if n == 0 or subset_sum < 0:
return False
result = (dfs(nums, n - 1, subset_sum - nums[n - 1])
or dfs(nums, n - 1, subset_sum))
return result
# find sum of array elements
total_sum = sum(nums)
# if total_sum is odd, it cannot be partitioned into equal sum subsets
if total_sum % 2 != 0:
return False
subset_sum = total_sum // 2
n = len(nums)
return dfs(tuple(nums), n - 1, subset_sum)