
Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

ECS 122A: Algorithm Design and Analysis Handout 2 UC Davis โ Charles Martel January. 26, 2009
The subset sum problem takes as input a set of integers L = {x 1 ,... , xn} and a target sum b and asks for a subset S โ L such that the sum of the items in S is at most b but as close to b as possible.
We can solve this by dynamic programming where we let T [i, j] = 1 if a subset of x 1 ,... , xi can sum to exactly j, otherwise T [i, j] = 0. To fill it in row by row we do the following (where T has n rows and b + 1 columns).
To initialize: T [1, x 1 ] = 1; rest of row 1 is all zeros T [i, 0] = 1 for i = 1, 2 ,... n
for i โ 2 to n for j โ 1 to xi โ 1 T [i, j] โ T [i โ 1 , j] for j โ xi to b T [i, j] โ 1 iff T [i โ 1 , j] = 1 or T [i โ 1 , j โ xi] = 1 T [i, j] โ 0 otherwise
Thus we easily fill in the table in ฮ(nb) time: this many entries, each taking O(1) time.