Find all distinct subset ( or subsequence ) sums of an array | Uses Dynamic Programming to find distinct subset sums ; dp [ i ] [ j ] would be true if arr [ 0. . i - 1 ] has a subset with sum equal to j . ; There is always a subset with 0 sum ; Fill dp [ ] [ ] in bottom up manner ; Sums that were achievable without current array element ; Print last row elements ; Driver code
function printDistSum ( arr , n ) { var sum = 0 ; for ( var i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; var dp = Array . from ( Array ( n + 1 ) , ( ) => Array ( sum + 1 ) . fill ( 0 ) ) ; for ( var i = 0 ; i <= n ; i ++ ) dp [ i ] [ 0 ] = true ; for ( var i = 1 ; i <= n ; i ++ ) { dp [ i ] [ arr [ i - 1 ] ] = true ; for ( var j = 1 ; j <= sum ; j ++ ) { if ( dp [ i - 1 ] [ j ] == true ) { dp [ i ] [ j ] = true ; dp [ i ] [ j + arr [ i - 1 ] ] = true ; } } } for ( var j = 0 ; j <= sum ; j ++ ) if ( dp [ n ] [ j ] == true ) document . write ( j + " " ) ; } var arr = [ 2 , 3 , 4 , 5 , 6 ] ; var n = arr . length ; printDistSum ( arr , n ) ;