Perfect Sum Problem | Function to print the subsets whose sum is equal to the given target K ; Create the new array with length equal to array set [ ] to create binary array as per n ( decimal number ) ; Convert the array into binary array ; Calculate the sum of this subset ; Check whether sum is equal to target if it is equal , then print the subset ; Function to find the subsets with sum K ; Calculate the total no . of subsets ; Run loop till total no . of subsets and call the function for each subset ; Driver code
function sumSubsets ( set , n , target ) { let x = new Array ( set . length ) ; let j = set . length - 1 ; while ( n > 0 ) { x [ j ] = n % 2 ; n = Math . floor ( n / 2 ) ; j -- ; } let sum = 0 ; for ( let i = 0 ; i < set . length ; i ++ ) if ( x [ i ] == 1 ) sum = sum + set [ i ] ; if ( sum == target ) { document . write ( " " ) ; for ( let i = 0 ; i < set . length ; i ++ ) if ( x [ i ] == 1 ) document . write ( set [ i ] + " " ) ; document . write ( " " ) ; } } function findSubsets ( arr , K ) { let x = Math . pow ( 2 , arr . length ) ; for ( let i = 1 ; i < x ; i ++ ) sumSubsets ( arr , i , K ) ; } let arr = [ 5 , 10 , 12 , 13 , 15 , 18 ] ; let K = 30 ; findSubsets ( arr , K ) ;