I found this code online somewhere and I'm trying to make sense of how it works. You supply the partitions() function with an integer and the code returns the number of distinct partitions that do NOT include repeating numbers (e.g. n = 5 -> 2 partitions (3,2) & (4,1)). I'd like to understand how exactly this recursive solution is managing this. I've been toying with the code, tracking the recursion calls, and I still can't quite understand how it works. Please help me understand.
def partitions(n):
memo = [[0 for _ in range(n + 2)] for _ in range(n + 2)]
return bricks(1, n, memo) - 1
def bricks(h, l, memo):
if memo[h][l] != 0:
return memo[h][l]
if l == 0:
return 1
if l < h:
return 0
memo[h][l] = (bricks(h + 1, l - h, memo)) + (bricks(h + 1, l, memo))
return memo[h][l]
At a glance, it looks like memoization along the lines of "equal partition subset sum".
You probably got the code from an answer here: https://leetcode.com/problems/partition-equal-subset-sum/
And you can find a description of how it works there or here: https://www.educative.io/courses/grokking-dynamic-programming-patterns-for-coding-interviews/3jEPRo5PDvx
The general idea here is to start with
nand ask "how can I computenfrom the subset of numbers split in each possible way"? (The split occurs at the recursive callmemo[h][l] = (bricks...). Each recursion may further split to try and form whatever difference is remaining from the previous split, etc.Note: It seems like "h" and "l" are backwards here if they are meant to be "high" and "low", respectively.