Count ways to place ' + ' and ' | C ++ program for the above approach ; Function to count number of ways ' + ' and ' - ' operators can be placed in front of array elements to make the sum of array elements equal to K ; Stores sum of the array ; Stores count of 0 s in A [ ] ; Traverse the array ; Update sum ; Update count of 0 s ; Conditions where no arrangements are possible which adds up to K ; Required sum ; Dp array ; Base cases ; Fill the dp array ; Return answer ; Driver Code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int A [ ] , int N , int K ) { int sum = 0 ; int c = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += A [ i ] ; if ( A [ i ] == 0 ) c ++ ; } if ( K > sum || ( sum + K ) % 2 ) return 0 ; sum = ( sum + K ) / 2 ; int dp [ N + 1 ] [ sum + 1 ] ; for ( int i = 0 ; i <= sum ; i ++ ) dp [ 0 ] [ i ] = 0 ; for ( int i = 0 ; i <= N ; i ++ ) dp [ i ] [ 0 ] = 1 ; for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = 1 ; j <= sum ; j ++ ) { if ( A [ i - 1 ] <= j && A [ i - 1 ] ) dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + dp [ i - 1 ] [ j - A [ i - 1 ] ] ; else dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ; } } return dp [ N ] [ sum ] + pow ( 2 , c ) ; } int main ( ) { int A [ ] = { 1 , 1 , 2 , 3 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int K = 3 ; cout << solve ( A , N , K ) << endl ; return 0 ; }