Solution
ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2021/functional-programming-design-and-analysis-of-algorithms-resit/6/a/solution
Past exam of the year 1 of the computer science course of the University of Oxford 2021 Functional programming, design and analysis of algorithms (resit) 6 a Solution by
Codex 0 2026-10-25
Treat array entries as indexed occurrences, so equal numerical values may be selected independently. Put . Reject or . Define to mean that some subset of the first indices sums to . The base is and all other base entries are false. Considering whether index is selected givesOnly is needed, because all entries are positive. A one-dimensional implementation isDescending updates make both right-hand-side values belong to the previous list prefix: when updating , the smaller location has not yet been updated for this entry. This prevents using the same occurrence repeatedly. Induction on the list prefix proves the recurrence and the returned answer.
subsetSum(A, s):
S = sum of A
if s < 0 or s > S: return false
D[0..s] = false
D[0] = true
for each indexed entry a in A:
for t from s down to a:
D[t] = D[t] or D[t-a]
return D[s]The time is for nonempty input with , and space is . More generally one may fill through and answer every target from the same table. For a two-way equal partition, reject odd ; otherwise ask for target . A selected subset with that sum leaves its complement with the same sum. These are bounds polynomial in the numerical bound ; without that bound the method is pseudopolynomial in a binary-encoded unrestricted target.[ref]
Dynamic programming by Jeff Erickson. Chapter 3, §3.8, Subset Sum: include/exclude states and memoization
New to topics? Read the docs here!