Find all distinct subset sums of an array (Tabulation)

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.

Hint

Building upon understanding of Find all distinct subset sums of an array (Memoization). Tabulation essentially reconstructs the cache.

Start with the foundation – the base cases, which are the simplest solutions. Then, layer by layer, use the results of the previous layers to calculate the solutions for the next level. This way, we systematically build up the entire solution, avoiding redundant calculations and ensuring efficiency. It is like building a pyramid.

The underlying calculation logic remains fundamentally identical to the original recursive approach, albeit executed in reverse order.

# Python implementation
def subsum(ls):
  cache = []
  cache.append(0)

  for i in ls:
    for j in [] + cache:
      cache.append(j + i)
  
  return cache

ls = [1, 2]
output = subsum(ls)
output.sort()

print(output)
// Javascript implementation
function subsum(list) {
  const cache = [];
  cache.push(0)

  for (const i of list) {
    for (const j of [...cache]) {
      cache.push(j + i)
    }
  }
  
  return cache;
}

const list = [1, 2];

console.log(subsum(list).sort((a, b) => a - b));