Back to course home
0% completed
Vote For New Content
dp / recursive solution
Mohammed Dh Abbas
Oct 14, 2024
class Solution: def canPartition(self, num): def solve(index, left, right, memo): # return from the cache if found if index in memo and str(left) + str(right) in memo[index]: return memo[index][str(left) + str(right)] # base case if index == len(num): return abs(left - right) # recursive with / without item at index result = min(solve(index + 1, left, right, memo), solve(index + 1, left - num[index], right + num[index], memo)) # cache the result if index not in memo: memo[index] = {} memo[index][str(left) + str(right)] = result return result return solve(0, sum(num), 0, {})
0
0
Comments
Comments
On this page
Problem Statement
Try it yourself