Memoization for subset sum [00RD]

This most definitely has overlapping subproblems. One simple approach is to use a 2D array c of size (n+1) \times (S + 1), so c[k][s] will store the output of \mathit {canAddTo}(k,s). It is also possible to use a dictionary with (k,s) pairs as keys; however, since 0 \leq k \leq n and 0 \leq s \leq S, using a 2D array is simpler and accomplishes exactly the same thing. (An array can be thought of as a special-purpose dictionary where the keys are consecutive integers starting from 0.)

Each entry depends only on entries either above it ( k is smaller), or above it and to the left ( k and s are both smaller), so we can fill it in row order or column order. In pseudocode:

\mathsf {for} k \gets 0 \dots n:
\mathsf {for} s \gets 0 \dots S:
\mathsf {if} s = 0:
c[k][s] \gets \mathsf {T}
\mathsf {elif} k = 0:
c[k][s] \gets \mathsf {F}
\mathsf {elif} x_k > s:
c[k][s] \gets c[k-1][s]
\mathsf {else}:
c[k][s] = c[k-1][s] \lor c[k-1][s-x_k]

Alternatively, we could use the technique of having a recursive function which checks first to see whether the required output is already in the array.

Since we fill in an (n+1) \times (S + 1) array, with \Theta (1) work required to fill in each cell, the algorithm takes \Theta (nS) time overall.