Count of Ways to obtain given Sum from the given Array elements | Function to call dfs ( ) to calculate the number of ways ; Function to count the number of ways ; Base Case : Reached the end of the array ; Sum is equal to the required sum ; Recursively check if required sum can be obtained by adding current element or by subtracting the current index element ; Driver Code
function findWays ( nums , S ) { return dfs ( nums , S , 0 , 0 ) ; } function dfs ( nums , S , curr_sum , index ) { if ( index == nums . length ) { if ( S == curr_sum ) return 1 ; else return 0 ; } return dfs ( nums , S , curr_sum + nums [ index ] , index + 1 ) + dfs ( nums , S , curr_sum - nums [ index ] , index + 1 ) ; } let S = 3 ; let arr = [ 1 , 2 , 3 , 4 , 5 ] ; let answer = findWays ( arr , S ) ; document . write ( answer ) ;