Back to problems
COMP2521
Recursion: Subset Sum
Recursion: Subset Sum
Given n non-negative integers and a target T, decide whether some subset (possibly empty) sums to exactly T.
Classic recursion: for itemi, branch take/skip —rec(i+1, sum+a[i])orrec(i+1, sum); hit whensum==T, stop ati==n.
Input: line 1 n T; line 2 n non-negative integers.
Output: YES or NO.
Example: 4 6 / 1 2 3 7 -> YES (1+2+3).
Samples
stdin
4 6 1 2 3 7
expected
YES
stdin
3 100 1 2 3
expected
NO
c-dcc
14