Count of Ways to obtain given Sum from the given Array elements | 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 ; Function to call dfs ( ) to calculate the number of ways ; Driver Code
def dfs ( nums , S , curr_sum , index ) : NEW_LINE INDENT if ( index == len ( nums ) ) : NEW_LINE INDENT if ( S == curr_sum ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT return ( dfs ( nums , S , curr_sum + nums [ index ] , index + 1 ) + dfs ( nums , S , curr_sum - nums [ index ] , index + 1 ) ) ; NEW_LINE DEDENT def findWays ( nums , S ) : NEW_LINE INDENT return dfs ( nums , S , 0 , 0 ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = 3 ; NEW_LINE arr = [ 1 , 2 , 3 , 4 , 5 ] ; NEW_LINE answer = findWays ( arr , S ) ; NEW_LINE print ( answer ) ; NEW_LINE DEDENT