This is not the same as this question: find all subsets that sum to a particular value
As I don't just have to count
the total number of subsets, but store all the subsets and return it.
I wrote a simple (exponential) algorithm that finds subsets summing up to a particular target:
Eg:
arr = [1,2,3,4,5,6,7,8]
Possible subsets:
5
4,1
3,2
This is my algorithm
n -> index of list (starts from the end)
target -> sum of subsets I want to create
arr = [1,2,3,4,5,6,7,8]
def subset_sum(arr, n, target, result):
if target == 0:
print result
return
if target < 0 or n < 0:
return False
subset_sum(arr, n-1, target - arr[n], result + str(arr[n]))
subset_sum(arr, n - 1, target, result)
print subset_sum(arr, len(arr) - 1, 5, '' )
I wish to opmitize this, possibly by memoization.
But I am having hard time figuring out what should be the state of this function (Should it be n
and target
?.. but I don't see it being repeated )