DP3: Subset Sum Revisited
San Skulrattanakulchai
October 11, 2018
Subset Sum Problem Revisited
- See DPV Exercise 6.22
- Problem: We are given a positive integer \(t\) and a sequence \(A = \langle a_1, a_2, \dots, a_n \rangle\) of (not necessarily distinct) \(n\) positive integers. We want to find out whether some subsequence of \(A\) sums to \(t\).
Dynamic Programming Solution
- Define \(m(i, v)\), for all \(0\le i \le n\) and \(0\le v\le t\), to be \[
m(i, v) =
\left\{
\begin{array}{ll}
\mbox{true}, & \mbox{if some subsequence of $a_1$, $a_2$, $\ldots$, $a_i$ sums to $v$}\\
\mbox{false}, & \mbox{otherwise.}
\end{array}
\right.
\]
- We seek \(m(n, t)\).
Optimal Substructure Property
- We have \(m(0, v)\) true if and only if \(v = 0\) because the empty sequence has exactly one subsequence—itself—and the empty sequence sums to 0.
- We also have \(m(i, 0)\) true for all \(1\le i\le n\) because the empty sequence is a subsequence of any sequence, and it sums to 0.
- Now let \(i, v\) be positive integers. Suppose the sequence \(\langle a_1, a_2, \dots, a_i\rangle\) contains a subsequence \(\langle b_1, b_2, \dots, b_j\rangle\) that sums to \(v\). These two mutually exclusive events exhaust all possibilites:
- Case 1: \(a_i=b_j\). Then the sequence \(\langle a_1, a_2, \dots, a_{i-1}\rangle\) contains the subsequence \(\langle b_1, b_2, \dots, b_{j-1}\rangle\) that sums to \(v-a_i\).
- Case 2: \(a_i\ne b_j\). Then the sequence \(\langle a_1, a_2, \dots, a_{i-1}\rangle\) contains the subsequence \(\langle b_1, b_2, \dots, b_j\rangle\) that sums to \(v\).
Recurrence
- The above reasoning gives us the following recurrence. \[
m(i, v) =
\left\{
\begin{array}{ll}
\mbox{true}, & \mbox{if $v = 0$} \\
\mbox{false}, & \mbox{if $i=0$, $v>0$} \\
m(i-1,v), & \mbox{if $i>0$, $a_i>v>0$} \\
m(i-1,v-a_i) \vee m(i-1,v), & \mbox{if $i>0$, $v\ge a_i>0$}
\end{array}
\right.
\]
Subset Sum Algorithm
- [Step 1] Fill in a table of \(m(\cdot, \cdot)\) values, We can fill the table row-by-row or column-by-column, with both the row and column indices increasing.
- [Step 2] Return the value \(m(n, t)\) as answer.
Running Time
- Step 1 fills out each table entry in \(O(1)\) time, \(O(nt)\) time total.
- Step 2 takes \(O(1)\) time.