Javatpoint Logo
Javatpoint Logo

Subset-Sum Problem

The Subset-Sum Problem is to find a subset's' of the given set S = (S1 S2 S3...Sn) where the elements of the set S are n positive integers in such a manner that s'∈S and sum of the elements of subset's' is equal to some positive integer 'X.'

The Subset-Sum Problem can be solved by using the backtracking approach. In this implicit tree is a binary tree. The root of the tree is selected in such a way that represents that no decision is yet taken on any input. We assume that the elements of the given set are arranged in increasing order:

S1 ≤ S2 ≤ S3... ≤ Sn

The left child of the root node indicated that we have to include 'S1' from the set 'S' and the right child of the root indicates that we have to execute 'S1'. Each node stores the total of the partial solution elements. If at any stage the sum equals to 'X' then the search is successful and terminates.

The dead end in the tree appears only when either of the two inequalities exists:

  • The sum of s' is too large i.e.
s'+ Si + 1 > X
  • The sum of s' is too small i.e.
Subset-Sum Problem

Example: Given a set S = (3, 4, 5, 6) and X =9. Obtain the subset sum using Backtracking approach.

Solution:


The implicit binary tree for the subset sum problem is shown as fig:

Subset-Sum Problem

The number inside a node is the sum of the partial solution elements at a particular level.

Thus, if our partial solution elements sum is equal to the positive integer 'X' then at that time search will terminate, or it continues if all the possible solution needs to be obtained.

Next TopicN Queens Problems




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


B.Tech / MCA