If no elements in the set then we can’t make any subset except for 0.

If sum needed is 0 then by returning the empty subset we can make the subset with sum 0.

Given – Set = arrA[], Size = n, sum = S

Now for every element in he set we have 2 options, either we include it or exclude it.

for any i^{th} element-

If include it => S = S-arrA[i], n=n-1

If exclude it => S, n=n-1.

Recursive Equation:Base Cases:
SubsetSum(arrA, n, S)= false, if sum > 0 and n == 0 SubsetSum(arrA, n, S)= true, if sum == 0 (return empty set)
Rest Cases
SubsetSum(arrA, n, S) = SubsetSum(arrA, n-1, S)|| SubsetSum(arrA, n-1, S-arrA[n-1])

How to track the elements.

Start from the bottom-right corner and backtrack and check from the True is coming.

If value in the cell above if false that means current cell has become true after including the current element. So include the current element and check for the sum = sum – current element.

Complete Code:

Output: From DP: true

__________________________________________________ Top Companies Interview Questions..-

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

Doesn’t that algorithm have a terrible worst case scenario?

Ankit

The problem statements are different. Print subset with required sum vs print *all* subsets with required sum. If you have a solution in mind which modifies the solution given on the page to print all subsets with lower time/space complexity; I would love to discuss.

Svein Asleik

Well, the problem was, check if there exists a subset. And the space complexity of the one given here could be reduced further by just keeping it in into one long long array with the size of the sum you want to add up to (O(S)). Gotta save it as numbers then, and not boolean.

Pravinth

In the recursive solution
solution[index] = 0;// do not select the element
currSum -= A[index]; //<<why this minus?.

cynical

Thank you so much for this solution.

TechUser2011

I’m trying to print this page, but the sidebar on the right is blocking too much of the page, including half of the code blocks. Can you please fix this problem? Maybe you can provide a way to print where the right sidebar is removed? Thank you.

9ddang

Hi, how do I trace it from the table when there is more than 1 subsets? For example, sum=5, array=[1,2,3,4,5]?