Subset Sum Problem Using A Dynamic Programming
Subset Sum Problem Using A Dynamic Programming
{ 2, 9, 10, 1, 99, 3}
{ 1, 3 }
1. Recursive method
2. Backtracking
3. Dynamic Programing
Here, we will solve this using Dynamic Programming.
Dynamic Programming
We create a boolean subset[][] and fill it in bottom up manner.
j=0 then subset[i][0] will be true as the sum for empty set is 0
subset[i][j] = subset[i-1][j-E1];
where E1 = array[i-1]
As if element E1 is included, then we need to find a subset with the first i-1
elements such that the sum is j - E1.
Dynamic Programming computes [i][j], for each 1 <= i <= n and 1 <= j <=
sum, which is true if subset with sum j can be found using items up to first i
items.
It uses value of smaller values i and j already computed. It has the same
asymptotic run-time as Memoization but no recursion overhead.
Steps:
1.We create a boolean subset[][] and fill it in bottom up manner.
2.The value of subset[i][j] will be true if there is a subset of set[0..j-1] with
sum equal to i., otherwise false.
3.Finally, we return subset[n][sum]
Complexity
Dynamic Programming
Worst case time complexity: Θ(n*sum)
Space complexity: Θ(sum)