Balanced expressions such that given positions have opening brackets | CPP code to find number of ways of arranging bracket with proper expressions ; function to calculate the number of proper bracket sequence ; hash array to mark the positions of opening brackets ; dp 2d array ; mark positions in hash array ; first position marked as 1 ; iterate and formulate the recurrences ; if position has a opening bracket ; return answer ; driver code ; positions where opening braces will be placed
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N  1000 NEW_LINE long long arrangeBraces ( int n , int pos [ ] , int k ) { bool h [ N ] ; int dp [ N ] [ N ] ; memset ( h , 0 , sizeof h ) ; memset ( dp , 0 , sizeof dp ) ; for ( int i = 0 ; i < k ; i ++ ) h [ pos [ i ] ] = 1 ; dp [ 0 ] [ 0 ] = 1 ; for ( int i = 1 ; i <= 2 * n ; i ++ ) { for ( int j = 0 ; j <= 2 * n ; j ++ ) { if ( h [ i ] ) { if ( j != 0 ) dp [ i ] [ j ] = dp [ i - 1 ] [ j - 1 ] ; else dp [ i ] [ j ] = 0 ; } else { if ( j != 0 ) dp [ i ] [ j ] = dp [ i - 1 ] [ j - 1 ] + dp [ i - 1 ] [ j + 1 ] ; else dp [ i ] [ j ] = dp [ i - 1 ] [ j + 1 ] ; } } } return dp [ 2 * n ] [ 0 ] ; } int main ( ) { int n = 3 ; int pos [ ] = { 2 } ; int k = sizeof ( pos ) / sizeof ( pos [ 0 ] ) ; cout << arrangeBraces ( n , pos , k ) ; return 0 ; }