27 Sum of Subsets Using Backtracking
27 Sum of Subsets Using Backtracking
Session -27
1
SUM OF SUBSETS
Problem Definition: Given n distinct positive numbers wi,
and m, find all subsets whose sums are m.
• Explicit Constraints :
• Xi = { j / j is an integer and 1 <= j <= n }
• Implicit Constraints :
1. No two xi’s are same
2. Sum of the chosen weights must be equal to m.
3. To avoid generation of multiple instances of the same
subsets)
x1=1 x1=4
x1=2
x1=3
3 4 5
2
6
SUBSET TREE FOR N = 4 ( FIXED – SIZED TUPLE )
x1=1 x1= 0
x3=1 x3 = 0
x4=1 x4=0
else if ( s + s [ k ] + s[ k+1 ] ≤ m )
x[ k ] = 0;
}
EX:- N=6, M=30, W [ 1:6 ]= { 5,10,12,13,15,18 }
PORTION OF STATE SPACE TREE GENERATED BY SUMOFSUB.
CIRCULAR NODES INDICATE SUBSETS WITH SUMS EQUAL TO M.
• Example 7.6 (Figure 7.10)
• n=6, w[1:6]={5,10,12,13,15,18}, m=30
SAMPLE QUESTIONS
11