Count of Ways to obtain given Sum from the given Array elements | Function to call dfs to calculate the number of ways ; If target + sum is odd or S exceeds sum ; No sultion exists ; Return the answer ; Driver Code
function knapSack ( nums , S ) { let sum = 0 ; for ( let i = 0 ; i < nums . length ; i ++ ) sum += nums [ i ] ; if ( sum < S || - sum > - S || ( S + sum ) % 2 == 1 ) return 0 ; let dp = new Array ( parseInt ( ( S + sum ) / 2 , 10 ) + 1 ) ; dp . fill ( 0 ) ; dp [ 0 ] = 1 ; for ( let num = 0 ; num < nums . length ; num ++ ) { for ( let i = dp . length - 1 ; i >= nums [ num ] ; i -- ) { dp [ i ] += dp [ i - nums [ num ] ] ; } } return dp [ dp . length - 1 ] ; } let S = 3 ; let arr = [ 1 , 2 , 3 , 4 , 5 ] ; let answer = knapSack ( arr , S ) ; document . write ( answer ) ;