Docsity

Subset Sum Handout | Algorithm Design | ECS 122A, Study notes of Computer Science

Toggle sidebar
bg1
ECS 122A: Algorithm Design and Analysis Handout 2
UC Davis โ€” Charles Martel January. 26, 2009
Subset Sum Handout
The subset sum problem takes as input a set of integers L={x1, . . . , xn}and a target sum
band asks for a subset SโІLsuch that the sum of the items in Sis at most bbut as close
to bas possible.
We can solve this by dynamic programming where we let T[i, j] = 1 if a subset of x1, . . . , 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 nrows and b+ 1 columns).
To initialize:
T[1, x1] = 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โ†xito 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.

Partial preview of the text

Download Subset Sum Handout | Algorithm Design | ECS 122A and more Study notes Computer Science in PDF only on Docsity!

ECS 122A: Algorithm Design and Analysis Handout 2 UC Davis โ€” Charles Martel January. 26, 2009

Subset Sum Handout

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.