📜  给定长度的戴克单词

📅  最后修改于: 2021-04-29 04:44:56             🧑  作者: Mango

给定一个整数n ,任务是计算可能长度为n的戴克词。 DYCK单词是仅包含字符‘X’‘Y’的单词,因此在单词的每个前缀中frequency(’X’)≥frequency(’Y’)

例子:

方法:

DYCK PATH包含不与AB线段交叉的n条水平线段和n条垂直线段。
该问题背后的主要思想是找到从(0,0)到(n,n)的DYCK路径总数。
为了解决这个问题,主要思想是找到(0,0)到(n,n)之间的曼哈顿距离的路径总数,并排除所有穿过线段AB的路径。


CD上的对称线。


FG-不对称线的对称线。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the count of
// Dyck Words of length n possible
long long int count_Dyck_Words(unsigned int n)
{
    // Calculate the value of 2nCn
    long long int res = 1;
    for (int i = 0; i < n; ++i) {
        res *= (2 * n - i);
        res /= (i + 1);
    }
  
    // Return 2nCn/(n+1)
    return (res / (n + 1));
}
  
// Driver Code
int main()
{
    int n = 5;
    cout << count_Dyck_Words(n);
    return 0;
}


Java
// Java implementation of the approach
class GFG
{
      
// Function to return the count of
// Dyck Words of length n possible
static int count_Dyck_Words( int n)
{
    // Calculate the value of 2nCn
    int res = 1;
    for (int i = 0; i < n; ++i) 
    {
        res *= (2 * n - i);
        res /= (i + 1);
    }
  
    // Return 2nCn/(n+1)
    return (res / (n + 1));
}
  
// Driver Code
public static void main(String[] args)
{
    int n = 5;
    System.out.println(count_Dyck_Words(n));
}
}
  
// This code is Contributed by Code_Mech.


Python3
# Python3 implementation of the approach 
  
# Function to return the count of 
# Dyck Words of length n possible 
def count_Dyck_Words(n) : 
      
    # Calculate the value of 2nCn 
    res = 1; 
    for i in range(n) :
        res *= (2 * n - i); 
        res //= (i + 1); 
      
    # Return 2nCn/(n+1) 
    return (res / (n + 1)); 
  
# Driver Code 
if __name__ == "__main__" : 
  
    n = 5; 
    print(count_Dyck_Words(n)); 
  
# This code is contributed by Ryuga


C#
// C# implementation of the approach
using System;
  
class GFG
{
      
// Function to return the count of
// Dyck Words of length n possible
static int count_Dyck_Words( int n)
{
    // Calculate the value of 2nCn
    int res = 1;
    for (int i = 0; i < n; ++i) 
    {
        res *= (2 * n - i);
        res /= (i + 1);
    }
  
    // Return 2nCn/(n+1)
    return (res / (n + 1));
}
  
// Driver Code
public static void Main()
{
    int n = 5;
    Console.WriteLine(count_Dyck_Words(n));
}
}
  
// This code is Contributed by Code_Mech.


PHP


输出:
42