I want to create a python program which returns all possible ways of writing an integer (say n) as a sum of r positive integers.
My code is as follows :
def f(n,r):
cache = {}
l1 = []
for i in range(1,n):
l1.append([i,n-i])
if r ==2 :
cache[tuple([n,r])] = l1
return l1
elif (n,r) in cache:
return cache[(n,r)]
else:
lr = []
for i in range (1,n):
for x in f(n-i,r-1):
x.append(i)
lr.append(x)
cache[tuple([n,r])] = lr
return lr
It works well till n = 20 for any value of r but after that it's really slow, which is kinda expected because recurrence is slow. How can I achieve this without using recurrence ?