There is a problem with the base clause suggested, since with it, you could also take s[n,0]
as an initial value.
A better stop clause to the recursive formula of subset-sum is s[i,xi] = true
. The idea is simple, the set {x1,x2,...,xi}
contains a subset that sums to xi
- it is the subset {xi}
. The recursion will later on take care of the rest, and if there is a subset summing to 0, it will find it.
According to this approach, the base clause is:
s[i,xi] = true (for each i)
s[0,j] = false (for each j)
And the recursive formula is:
s[i,j] = s[i-1,j] OR s[i-1,j-xi]
To get which elements are actually in the subset, you will need to follow the matrix you built with your dynamic programming. "follow" the choices done by the matrix, and stick to a path that yields true until you find a "stop clause" (s == xi)
It can be described recursively with:
getSubset(i,s):
if s[i-1,s]: //there is a solution without choosing xi
return getSubset(i-1, s)
if (xi == s): //true base clause
l <- new list
l.append(xi)
return l
if s[i -1, s-xi]: //there is a solution when choosing xi
l <- getSubset(i-1,s-xi)
l.append(xi)
return l
It resembles a lot (make sure you understand why): How to find which elements are in the bag, using Knapsack Algorithm [and not only the bag's value]?