Given a list of numbers, find all distinct sums that can be generated from the subsets of the given list and return them in increasing order.
This algorithm uses memoization to improve performance. It's same as the recursive version of Find all distinct subset sums of an array, but with a special 'cache' to store results. The 'cache key' is crucial. It's how we identify and store past results. Sometimes we need one key, sometimes multiple keys. We add code to:
cache = {} def subsum(ls): if len(ls) <= 0: return [0] if len(ls) not in cache: l = subsum(ls[1:]) cache[len(ls)] = l + [x + ls[0] for x in l] return cache[len(ls)] ls = [1, 2] output = subsum(ls) output.sort() print(output)
const cache = []; function subsum(list) { if (list.length <= 0) { return [0]; } if (cache[list.length] === undefined) { const ls = subsum(list.slice(1)); cache[list.length] = [...ls, ...ls.map(x => x + list[0])]; } return cache[list.length]; } const list = [1, 2]; console.log(subsum(list).sort((a, b) => a - b));