Open In App
Related Articles

Number of ways to partition a string into two balanced subsequences

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Given a string ‘S’ consisting of open and closed brackets, the task is find the number of ways in which each character of ‘S’ can be assigned to either a string ‘X’ or string ‘Y’ (both initially empty) such that the strings formed by X and Y are balanced. It can be assumed that ‘S’ is itself balanced.

Examples: 

Input: S = "(())"
Output: 6
Valid assignments are :
X = "(())" and Y = "" [All characters in X]
X = "" and Y = "(())" [Nothing in X]
X = "()" and Y = "()" [1st and 3rd characters in X]
X = "()" and Y = "()" [2nd and 3rd characters in X]
X = "()" and Y = "()" [2nd and 4th characters in X]
X = "()" and Y = "()" [1st and 4th characters in X]
Input: S = "()()"
Output: 4
X = "()()", Y = ""
X = "()", Y = "()" [1st and 2nd in X]
X = "()", Y = "" [1st and 4th in X]
X = "", Y = "()()"

A simple approach: 

We can generate every possible way of assigning the characters, and check if the strings formed are balanced or not. There are 2n assignments, valid or invalid, and it takes O(n) time to check if the strings formed are balanced or not. Therefore the time complexity of this approach is O(n * 2n).

An efficient approach (Dynamic programming): 

We can solve this problem in a more efficient manner using Dynamic Programming. We can describe the current state of assignment using three variables: the index i of the character to be assigned, and the strings formed by X and Y up to that state. Passing the whole strings to function calls will result in high memory requirements, so we can replace them with count variables cx and cy. We will increment the count variable for every opening bracket and decrement it for every closing bracket. The time and space complexity of this approach is O(n3).

Below is the implementation of the above approach:

C++

// C++ implementation of
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// For maximum length of input string
const int MAX = 10;
 
// Declaring the DP table
int F[MAX][MAX][MAX];
 
// Function to calculate the
// number of valid assignments
int noOfAssignments(string& S, int& n, int i,
                    int c_x, int c_y)
{
    if (F[i][c_x][c_y] != -1)
        return F[i][c_x][c_y];
 
    if (i == n) {
 
        // Return 1 if both
        // subsequences are balanced
        F[i][c_x][c_y] = !c_x && !c_y;
        return F[i][c_x][c_y];
    }
 
    // Increment the count
    // if it an opening bracket
    if (S[i] == '(') {
        F[i][c_x][c_y]
            = noOfAssignments(S, n, i + 1,
                              c_x + 1, c_y)
              + noOfAssignments(S, n, i + 1,
                                c_x, c_y + 1);
        return F[i][c_x][c_y];
    }
 
    F[i][c_x][c_y] = 0;
 
    // Decrement the count
    // if it a closing bracket
    if (c_x)
        F[i][c_x][c_y]
            += noOfAssignments(S, n, i + 1,
                               c_x - 1, c_y);
 
    if (c_y)
        F[i][c_x][c_y]
            += noOfAssignments(S, n, i + 1,
                               c_x, c_y - 1);
 
    return F[i][c_x][c_y];
}
 
// Driver code
int main()
{
    string S = "(())";
    int n = S.length();
 
    // Initializing the DP table
    memset(F, -1, sizeof(F));
 
    // Initial value for c_x
    // and c_y is zero
    cout << noOfAssignments(S, n, 0, 0, 0);
 
    return 0;
}

                    

Java

// Java implementation of the above approach
class GFG
{
 
    // For maximum length of input string
    static int MAX = 10;
 
    // Declaring the DP table
    static int[][][] F = new int[MAX][MAX][MAX];
 
    // Function to calculate the
    // number of valid assignments
    static int noOfAssignments(String s, int n,
                               int i, int c_x, int c_y)
    {
        if (F[i][c_x][c_y] != -1)
            return F[i][c_x][c_y];
        if (i == n)
        {
 
            // Return 1 if both
            // subsequences are balanced
            F[i][c_x][c_y] = (c_x == 0 &&
                              c_y == 0) ? 1 : 0;
            return F[i][c_x][c_y];
        }
 
        // Increment the count
        // if it an opening bracket
        if (s.charAt(i) == '(')
        {
            F[i][c_x][c_y] = noOfAssignments(s, n, i + 1,
                                             c_x + 1, c_y) +
                             noOfAssignments(s, n, i + 1,
                                             c_x, c_y + 1);
            return F[i][c_x][c_y];
        }
 
        F[i][c_x][c_y] = 0;
 
        // Decrement the count
        // if it a closing bracket
        if (c_x != 0)
            F[i][c_x][c_y] += noOfAssignments(s, n, i + 1,
                                              c_x - 1, c_y);
 
        if (c_y != 0)
            F[i][c_x][c_y] += noOfAssignments(s, n, i + 1,
                                              c_x, c_y - 1);
 
        return F[i][c_x][c_y];
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String s = "(())";
        int n = s.length();
 
        // Initializing the DP table
        for (int i = 0; i < MAX; i++)
            for (int j = 0; j < MAX; j++)
                for (int k = 0; k < MAX; k++)
                    F[i][j][k] = -1;
 
        // Initial value for c_x
        // and c_y is zero
        System.out.println(noOfAssignments(s, n, 0, 0, 0));
    }
}
 
// This code is contributed by
// sanjeev2552

                    

Python3

# Python3 implementation of above approach
 
# For maximum length of input string
MAX = 10
 
# Declaring the DP table
F = [[[-1 for i in range(MAX)]
          for j in range(MAX)]
          for k in range(MAX)]
 
# Function to calculate the number
# of valid assignments
def noOfAssignments(S, n, i, c_x, c_y):
 
    if F[i][c_x][c_y] != -1:
        return F[i][c_x][c_y]
 
    if i == n:
 
        # Return 1 if both subsequences are balanced
        F[i][c_x][c_y] = not c_x and not c_y
        return F[i][c_x][c_y]
 
    # Increment the count if
    # it is an opening bracket
    if S[i] == '(':
        F[i][c_x][c_y] = \
            noOfAssignments(S, n, i + 1, c_x + 1, c_y) + \
            noOfAssignments(S, n, i + 1, c_x, c_y + 1)
         
        return F[i][c_x][c_y]
 
    F[i][c_x][c_y] = 0
 
    # Decrement the count
    # if it a closing bracket
    if c_x:
        F[i][c_x][c_y] += \
            noOfAssignments(S, n, i + 1, c_x - 1, c_y)
 
    if c_y:
        F[i][c_x][c_y] += \
            noOfAssignments(S, n, i + 1, c_x, c_y - 1)
 
    return F[i][c_x][c_y]
 
# Driver code
if __name__ == "__main__":
 
    S = "(())"
    n = len(S)
 
    # Initial value for c_x and c_y is zero
    print(noOfAssignments(S, n, 0, 0, 0))
 
# This code is contributed by Rituraj Jain

                    

C#

// C# implementation of the above approach
using System;
     
class GFG
{
 
    // For maximum length of input string
    static int MAX = 10;
 
    // Declaring the DP table
    static int[,,] F = new int[MAX, MAX, MAX];
 
    // Function to calculate the
    // number of valid assignments
    static int noOfAssignments(String s, int n,
                         int i, int c_x, int c_y)
    {
        if (F[i, c_x, c_y] != -1)
            return F[i, c_x, c_y];
             
        if (i == n)
        {
 
            // Return 1 if both
            // subsequences are balanced
            F[i, c_x, c_y] = (c_x == 0 &&
                              c_y == 0) ? 1 : 0;
            return F[i, c_x, c_y];
        }
 
        // Increment the count
        // if it an opening bracket
        if (s[i] == '(')
        {
            F[i, c_x, c_y] = noOfAssignments(s, n, i + 1,
                                             c_x + 1, c_y) +
                             noOfAssignments(s, n, i + 1,
                                             c_x, c_y + 1);
            return F[i, c_x, c_y];
        }
 
        F[i, c_x, c_y] = 0;
 
        // Decrement the count
        // if it a closing bracket
        if (c_x != 0)
            F[i, c_x, c_y] += noOfAssignments(s, n, i + 1,
                                              c_x - 1, c_y);
 
        if (c_y != 0)
            F[i, c_x, c_y] += noOfAssignments(s, n, i + 1,
                                              c_x, c_y - 1);
 
        return F[i, c_x, c_y];
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        String s = "(())";
        int n = s.Length;
 
        // Initializing the DP table
        for (int i = 0; i < MAX; i++)
            for (int j = 0; j < MAX; j++)
                for (int k = 0; k < MAX; k++)
                    F[i, j, k] = -1;
 
        // Initial value for c_x
        // and c_y is zero
        Console.WriteLine(noOfAssignments(s, n, 0, 0, 0));
    }
}
 
// This code is contributed by PrinciRaj1992

                    

Javascript

<script>
// Javascript implementation of the above approach
     
    // For maximum length of input string
    let MAX = 10;
     
    // Declaring the DP table
    let F = new Array(MAX);
    for(let i = 0; i < MAX; i++)
    {
        F[i] = new Array(MAX);
        for(let j = 0; j < MAX; j++)
        {
            F[i][j] = new Array(MAX);
            for(let k = 0; k < MAX; k++)
            {
                F[i][j][k] = -1;
            }
        }
    }
     
    // Function to calculate the
    // number of valid assignments
    function noOfAssignments(s,n,i,c_x,c_y)
    {
        if (F[i][c_x][c_y] != -1)
            return F[i][c_x][c_y];
        if (i == n)
        {
   
            // Return 1 if both
            // subsequences are balanced
            F[i][c_x][c_y] = (c_x == 0 &&
                              c_y == 0) ? 1 : 0;
            return F[i][c_x][c_y];
        }
   
        // Increment the count
        // if it an opening bracket
        if (s.charAt(i) == '(')
        {
            F[i][c_x][c_y] = noOfAssignments(s, n, i + 1,
                                             c_x + 1, c_y) +
                             noOfAssignments(s, n, i + 1,
                                             c_x, c_y + 1);
            return F[i][c_x][c_y];
        }
   
        F[i][c_x][c_y] = 0;
   
        // Decrement the count
        // if it a closing bracket
        if (c_x != 0)
            F[i][c_x][c_y] += noOfAssignments(s, n, i + 1,
                                              c_x - 1, c_y);
   
        if (c_y != 0)
            F[i][c_x][c_y] += noOfAssignments(s, n, i + 1,
                                              c_x, c_y - 1);
   
        return F[i][c_x][c_y];
    }
     
    // Driver Code
    let  s = "(())";
    let n = s.length;
     
    // Initial value for c_x
    // and c_y is zero
    document.write(noOfAssignments(s, n, 0, 0, 0));
 
// This code is contributed by rag2127
</script>

                    

Output
6








Another approach : Using DP Tabulation method ( Iterative approach )

In this approach we use Dp to store computation of subproblems and get the desired output without the help of recursion.

Steps to solve this problem :

  • Create a 3D table F to store the solution of the subproblems and initialize it with 0.
  • Initialize the table F with base cases
  • Now Iterate over subproblems to get the value of current problem form previous computation of subproblems stored in DP
  • Return the final solution stored in F[0][0][0]

Implementation :

C++

#include <bits/stdc++.h>
using namespace std;
 
int noOfAssignments(string& S, int& n) {
    // For maximum length of input string
    const int MAX = n + 1;
 
    // Declaring the DP table
    int F[MAX][MAX][MAX];
    memset(F, 0, sizeof(F));
 
    // Base case: both subsequences are balanced
    for(int i=0; i<=n; i++) {
        F[i][0][0] = 1;
    }
 
    // Filling up the table in a bottom-up manner
    for(int i=n-1; i>=0; i--) {
        for(int c_x=0; c_x<=n; c_x++) {
            for(int c_y=0; c_y<=n; c_y++) {
                // If current character is an opening bracket
                if(S[i] == '(') {
                    F[i][c_x][c_y] = F[i+1][c_x+1][c_y] + F[i+1][c_x][c_y+1];
                }
                // If current character is a closing bracket
                else {
                    F[i][c_x][c_y] = 0;
                    if(c_x > 0) {
                        F[i][c_x][c_y] += F[i+1][c_x-1][c_y];
                    }
                    if(c_y > 0) {
                        F[i][c_x][c_y] += F[i+1][c_x][c_y-1];
                    }
                }
            }
        }
    }
 
    // Final result
    return F[0][0][0];
}
 
int main()
{
    string S = "(())";
    int n = S.length();
 
    cout << noOfAssignments(S, n);
 
    return 0;
}

                    

Java

import java.util.*;
 
public class BalancedParenthesesCount {
 
    public static int noOfAssignments(String S, int n) {
        // For maximum length of input string
        final int MAX = n + 2;
 
        // Declaring the DP table
        int[][][] F = new int[MAX][MAX][MAX];
        for (int i = 0; i < MAX; i++) {
            for (int j = 0; j < MAX; j++) {
                Arrays.fill(F[i][j], 0);
            }
        }
 
        // Base case: both subsequences are balanced
        for (int i = 0; i <= n; i++) {
            F[i][0][0] = 1;
        }
 
        // Filling up the table in a bottom-up manner
        for (int i = n - 1; i >= 0; i--) {
            for (int c_x = 0; c_x <= n; c_x++) {
                for (int c_y = 0; c_y <= n; c_y++) {
                    // If current character is an opening bracket
                    if (S.charAt(i) == '(') {
                        F[i][c_x][c_y] = F[i + 1][c_x + 1][c_y] + F[i + 1][c_x][c_y + 1];
                    }
                    // If current character is a closing bracket
                    else {
                        F[i][c_x][c_y] = 0;
                        if (c_x > 0) {
                            F[i][c_x][c_y] += F[i + 1][c_x - 1][c_y];
                        }
                        if (c_y > 0) {
                            F[i][c_x][c_y] += F[i + 1][c_x][c_y - 1];
                        }
                    }
                }
            }
        }
 
        // Final result
        return F[0][0][0];
    }
 
    public static void main(String[] args) {
        String S = "(())";
        int n = S.length();
 
        System.out.println(noOfAssignments(S, n));
    }
}

                    

Python3

# This program counts the number of ways to assign parentheses to a string
# such that the resulting expression is balanced.
 
class BalancedParenthesesCount:
 
    @staticmethod
    def noOfAssignments(S, n):
        """Counts the number of ways to assign parentheses to a string
        such that the resulting expression is balanced.
 
        Args:
            S: The string.
            n: The length of the string.
 
        Returns:
            The number of ways to assign parentheses to the string such that the
            resulting expression is balanced.
        """
 
        # Initialize the dynamic programming table.
        F = [[[0 for _ in range(n + 2)] for _ in range(n + 2)] for _ in range(n + 2)]
 
        # Base case: Both subsequences are balanced.
        for i in range(n + 1):
            F[i][0][0] = 1
 
        # Fill up the table in a bottom-up manner.
        for i in range(n - 1, -1, -1):
            for c_x in range(n + 1):
                for c_y in range(n + 1):
                    # If the current character is an opening bracket.
                    if S[i] == "(":
                        F[i][c_x][c_y] = F[i + 1][c_x + 1][c_y] + F[i + 1][c_x][c_y + 1]
                    # If the current character is a closing bracket.
                    else:
                        F[i][c_x][c_y] = 0
                        if c_x > 0:
                            F[i][c_x][c_y] += F[i + 1][c_x - 1][c_y]
                        if c_y > 0:
                            F[i][c_x][c_y] += F[i + 1][c_x][c_y - 1]
 
        # Final result.
        return F[0][0][0]
 
 
if __name__ == "__main__":
    S = "(())"
    n = len(S)
 
    print(BalancedParenthesesCount.noOfAssignments(S, n))

                    

C#

using System;
 
class GFG {
    static int noOfAssignments(string S, ref int n)
    {
        // For maximum length of input string
        const int MAX = 101;
 
        // Declaring the DP table
        int[, , ] F = new int[MAX, MAX, MAX];
 
        // Initialize the DP table to 0
        for (int i = 0; i < MAX; i++) {
            for (int j = 0; j < MAX; j++) {
                for (int k = 0; k < MAX; k++) {
                    F[i, j, k] = 0;
                }
            }
        }
 
        // Base case: both subsequences are balanced
        for (int i = 0; i <= n; i++) {
            F[i, 0, 0] = 1;
        }
 
        // Filling up the table in a bottom-up manner
        for (int i = n - 1; i >= 0; i--) {
            for (int c_x = 0; c_x <= n; c_x++) {
                for (int c_y = 0; c_y <= n; c_y++) {
                    // If current character is an opening
                    // bracket
                    if (S[i] == '(') {
                        F[i, c_x, c_y]
                            = F[i + 1, c_x + 1, c_y]
                              + F[i + 1, c_x, c_y + 1];
                    }
                    // If current character is a closing
                    // bracket
                    else {
                        F[i, c_x, c_y] = 0;
                        if (c_x > 0) {
                            F[i, c_x, c_y]
                                += F[i + 1, c_x - 1, c_y];
                        }
                        if (c_y > 0) {
                            F[i, c_x, c_y]
                                += F[i + 1, c_x, c_y - 1];
                        }
                    }
                }
            }
        }
 
        // Final result
        return F[0, 0, 0];
    }
 
    static void Main()
    {
        string S = "(())";
        int n = S.Length;
 
        Console.WriteLine(noOfAssignments(S, ref n));
    }
}

                    

Javascript

//Javascript code for the above approach
 
function noOfAssignments(S) {
    // For maximum length of input string
    const MAX = S.length + 2;
 
    // Declaring the DP table
    const F = new Array(MAX).fill(null).map(() =>
        new Array(MAX).fill(null).map(() =>
            new Array(MAX).fill(0)
        )
    );
 
    // Base case: both subsequences are balanced
    for (let i = 0; i <= S.length; i++) {
        F[i][0][0] = 1;
    }
 
    // Filling up the table in a bottom-up manner
    for (let i = S.length - 1; i >= 0; i--) {
        for (let c_x = 0; c_x <= S.length; c_x++) {
            for (let c_y = 0; c_y <= S.length; c_y++) {
                // If current character is an opening bracket
                if (S[i] === '(') {
                    F[i][c_x][c_y] = F[i + 1][c_x + 1][c_y] + F[i + 1][c_x][c_y + 1];
                }
                // If current character is a closing bracket
                else {
                    F[i][c_x][c_y] = 0;
                    if (c_x > 0) {
                        F[i][c_x][c_y] += F[i + 1][c_x - 1][c_y];
                    }
                    if (c_y > 0) {
                        F[i][c_x][c_y] += F[i + 1][c_x][c_y - 1];
                    }
                }
            }
        }
    }
 
    // Final result
    return F[0][0][0];
}
 
const S = "(())";
console.log(noOfAssignments(S));

                    

Output:

6

Time complexity : O(N^3)

Auxiliary Space : O(N^3)

Optimized Dynamic Programming approach: 

We can create a prefix array to store the count variable ci for the substring S[0 : i + 1]. We can observe that the sum of c_x and c_y will always be equal to the count variable for the whole string. By exploiting this property, we can reduce our dynamic programming approach to two states. A prefix array can be created in linear complexity, so the time and space complexity of this approach is O(n2). 

Implementation:

C++

// C++ implementation of
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// For maximum length of input string
const int MAX = 10;
 
// Declaring the DP table
int F[MAX][MAX];
 
// Declaring the prefix array
int C[MAX];
 
// Function to calculate the
// number of valid assignments
int noOfAssignments(string& S, int& n,
                    int i, int c_x)
{
    if (F[i][c_x] != -1)
        return F[i][c_x];
 
    if (i == n) {
 
        // Return 1 if X is
        // balanced.
        F[i][c_x] = !c_x;
        return F[i][c_x];
    }
 
    int c_y = C[i] - c_x;
 
    // Increment the count
    // if it an opening bracket
    if (S[i] == '(') {
        F[i][c_x]
            = noOfAssignments(S, n, i + 1,
                              c_x + 1)
              + noOfAssignments(S, n,
                                i + 1, c_x);
        return F[i][c_x];
    }
 
    F[i][c_x] = 0;
 
    // Decrement the count
    // if it a closing bracket
    if (c_x)
        F[i][c_x]
            += noOfAssignments(S, n,
                               i + 1, c_x - 1);
 
    if (c_y)
        F[i][c_x]
            += noOfAssignments(S, n,
                               i + 1, c_x);
 
    return F[i][c_x];
}
 
// Driver code
int main()
{
    string S = "()";
    int n = S.length();
 
    // Initializing the DP table
    memset(F, -1, sizeof(F));
 
    C[0] = 0;
 
    // Creating the prefix array
    for (int i = 0; i < n; ++i)
        if (S[i] == '(')
            C[i + 1] = C[i] + 1;
        else
            C[i + 1] = C[i] - 1;
 
    // Initial value for c_x
    // and c_y is zero
    cout << noOfAssignments(S, n, 0, 0);
 
    return 0;
}

                    

Java

// Java implementation of the approach
 
public class GFG {
 
// For maximum length of input string
    static int MAX = 10;
 
// Declaring the DP table
    static int F[][] = new int[MAX][MAX];
 
// Declaring the prefix array
    static int C[] = new int[MAX];
 
// Function to calculate the
// number of valid assignments
    static int noOfAssignments(String S, int n, int i, int c_x) {
        if (F[i][c_x] != -1) {
            return F[i][c_x];
        }
 
        if (i == n) {
 
            // Return 1 if X is
            // balanced.
            if (c_x == 1) {
                F[i][c_x] = 0;
            } else {
                F[i][c_x] = 1;
            }
 
            return F[i][c_x];
        }
 
        int c_y = C[i] - c_x;
 
        // Increment the count
        // if it an opening bracket
        if (S.charAt(i) == '(') {
            F[i][c_x]
                    = noOfAssignments(S, n, i + 1,
                            c_x + 1)
                    + noOfAssignments(S, n,
                            i + 1, c_x);
            return F[i][c_x];
        }
 
        F[i][c_x] = 0;
 
        // Decrement the count
        // if it a closing bracket
        if (c_x == 1) {
            F[i][c_x]
                    += noOfAssignments(S, n,
                            i + 1, c_x - 1);
        }
 
        if (c_y == 1) {
            F[i][c_x]
                    += noOfAssignments(S, n,
                            i + 1, c_x);
        }
 
        return F[i][c_x];
    }
 
// Driver code
    public static void main(String[] args) {
        String S = "()";
        int n = S.length();
 
        // Initializing the DP table
        for (int i = 0; i < MAX; i++) {
            for (int j = 0; j < MAX; j++) {
                F[i][j] = -1;
            }
        }
 
        C[0] = 0;
 
        // Creating the prefix array
        for (int i = 0; i < n; ++i) {
            if (S.charAt(i) == '(') {
                C[i + 1] = C[i] + 1;
            } else {
                C[i + 1] = C[i] - 1;
            }
        }
 
        // Initial value for c_x
        // and c_y is zero
        System.out.println(noOfAssignments(S, n, 0, 0));
 
    }
}
// This code is contributed by 29AjayKumar

                    

Python3

# Python3 implementation of above approach
 
# For maximum length of input string
MAX = 10
 
# Declaring the DP table
F = [[-1 for i in range(MAX)]
         for j in range(MAX)]
 
# Declaring the prefix array
C = [None] * MAX
 
# Function to calculate the
# number of valid assignments
def noOfAssignments(S, n, i, c_x):
 
    if F[i][c_x] != -1:
        return F[i][c_x]
 
    if i == n:
 
        # Return 1 if X is balanced.
        F[i][c_x] = not c_x
        return F[i][c_x]
 
    c_y = C[i] - c_x
 
    # Increment the count
    # if it is an opening bracket
    if S[i] == '(':
        F[i][c_x] = \
            noOfAssignments(S, n, i + 1, c_x + 1) + \
            noOfAssignments(S, n, i + 1, c_x)
         
        return F[i][c_x]
 
    F[i][c_x] = 0
 
    # Decrement the count if it is a closing bracket
    if c_x:
        F[i][c_x] += \
            noOfAssignments(S, n, i + 1, c_x - 1)
 
    if c_y:
        F[i][c_x] += \
            noOfAssignments(S, n, i + 1, c_x)
 
    return F[i][c_x]
 
# Driver code
if __name__ == "__main__":
 
    S = "()"
    n = len(S)
 
    C[0] = 0
 
    # Creating the prefix array
    for i in range(0, n):
        if S[i] == '(':
            C[i + 1] = C[i] + 1
        else:
            C[i + 1] = C[i] - 1
 
    # Initial value for c_x and c_y is zero
    print(noOfAssignments(S, n, 0, 0))
 
# This code is contributed by Rituraj Jain

                    

C#

// C# implementation of the approach
  
using System;
public class GFG {
  
// For maximum length of input string
    static int MAX = 10;
  
// Declaring the DP table
    static int[,] F = new int[MAX,MAX];
  
// Declaring the prefix array
    static int[] C = new int[MAX];
  
// Function to calculate the
// number of valid assignments
    static int noOfAssignments(string S, int n, int i, int c_x) {
        if (F[i,c_x] != -1) {
            return F[i,c_x];
        }
  
        if (i == n) {
  
            // Return 1 if X is
            // balanced.
            if (c_x == 1) {
                F[i,c_x] = 0;
            } else {
                F[i,c_x] = 1;
            }
  
            return F[i,c_x];
        }
  
        int c_y = C[i] - c_x;
  
        // Increment the count
        // if it an opening bracket
        if (S[i] == '(') {
            F[i,c_x]
                    = noOfAssignments(S, n, i + 1,
                            c_x + 1)
                    + noOfAssignments(S, n,
                            i + 1, c_x);
            return F[i,c_x];
        }
  
        F[i,c_x] = 0;
  
        // Decrement the count
        // if it a closing bracket
        if (c_x == 1) {
            F[i,c_x]
                    += noOfAssignments(S, n,
                            i + 1, c_x - 1);
        }
  
        if (c_y == 1) {
            F[i,c_x]
                    += noOfAssignments(S, n,
                            i + 1, c_x);
        }
  
        return F[i,c_x];
    }
  
// Driver code
    public static void Main() {
        string S = "()";
        int n = S.Length;
  
        // Initializing the DP table
        for (int i = 0; i < MAX; i++) {
            for (int j = 0; j < MAX; j++) {
                F[i,j] = -1;
            }
        }
  
        C[0] = 0;
  
        // Creating the prefix array
        for (int i = 0; i < n; ++i) {
            if (S[i] == '(') {
                C[i + 1] = C[i] + 1;
            } else {
                C[i + 1] = C[i] - 1;
            }
        }
  
        // Initial value for c_x
        // and c_y is zero
        Console.WriteLine(noOfAssignments(S, n, 0, 0));
  
    }
}
// This code is contributed by Ita_c.

                    

Javascript

<script>
// Javascript implementation of the approach
  
// For maximum length of input string
var MAX = 10;
  
// Declaring the DP table
var F = Array.from(Array(MAX), ()=>Array(MAX).fill(0));
  
// Declaring the prefix array
var C = Array(MAX).fill(0);
  
// Function to calculate the
// number of valid assignments
function noOfAssignments(S, n, i, c_x) {
        if (F[i][c_x] != -1) {
            return F[i][c_x];
        }
  
        if (i == n) {
  
            // Return 1 if X is
            // balanced.
            if (c_x == 1) {
                F[i][c_x] = 0;
            } else {
                F[i][c_x] = 1;
            }
  
            return F[i][c_x];
        }
  
        var c_y = C[i] - c_x;
  
        // Increment the count
        // if it an opening bracket
        if (S[i] == '(') {
            F[i][c_x]
                    = noOfAssignments(S, n, i + 1,
                            c_x + 1)
                    + noOfAssignments(S, n,
                            i + 1, c_x);
            return F[i][c_x];
        }
  
        F[i][c_x] = 0;
  
        // Decrement the count
        // if it a closing bracket
        if (c_x == 1) {
            F[i][c_x]
                    += noOfAssignments(S, n,
                            i + 1, c_x - 1);
        }
  
        if (c_y == 1) {
            F[i][c_x]
                    += noOfAssignments(S, n,
                            i + 1, c_x);
        }
  
        return F[i][c_x];
    }
  
// Driver code
var S = "()";
var n = S.length;
 
// Initializing the DP table
for(var i = 0; i < MAX; i++) {
    for(var j = 0; j < MAX; j++) {
        F[i][j] = -1;
    }
}
 
C[0] = 0;
 
// Creating the prefix array
for (var i = 0; i < n; ++i) {
    if (S[i] == '(') {
        C[i + 1] = C[i] + 1;
    } else {
        C[i + 1] = C[i] - 1;
    }
}
 
// Initial value for c_x
// and c_y is zero
document.write(noOfAssignments(S, n, 0, 0) + "<br>");
 
// This code is contributed by rrrtnx.
</script>

                    

Output
2










Last Updated : 07 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Similar Reads