All Construct with Tabulation

Updated: 01 February 2024

Problem

The same problem as the All Construct Memoization Problem but implemented using the tabular style in the previous problems

This is almost the same as the Count Construct solution but instead of incrementing the count we define the new running combination to reach a current position while retaining all other values that have reached that position thus far

For reference see the resulting array for a certain combination:

Tabulation Implementation

The implementation of this can be seen below:

dynamic-programming/tabulation/all-construct.ts
export const countConstruct = (target: string, subs: string[]): string[][] => {
  const table = new Array(target.length + 1)
    .fill(undefined)
    .map<string[][]>(() => []);

  table[0] = [[]];

  for (let index = 0; index <= target.length; index++) {
    const element = table[index];
    for (const sub of subs) {
      const fromIndex = target.slice(index);
      if (fromIndex.startsWith(sub)) {
        const nextIndex = index + sub.length;
        const newValues = element.map((el) => [...el, sub]);

        table[nextIndex].push(...newValues);
      }
    }
  }

  return table[target.length];
};

In the above, the time complexity $O(n^m)$ and space complexity $O(n^m)$. While the resulting complexity is pretty bad it is the best we’re going to get for this solution since it explicitly needs a list of all possible combinations