考虑一个左上角索引为(0,0)的anxn网格。 Dyck路径是从左下角(即(n-1,0)到右上角,即(0,n-1))位于对角单元格(或从左下角到右上角的线上的单元格)上方的阶梯步道。
任务是计算从(n-1,0)到(0,n-1)的Dyck路径数。
例子 :
Input : n = 1
Output : 1
Input : n = 2
Output : 2
Input : n = 3
Output : 5
Input : n = 4
Output : 14
从(n-1,0)到(0,n-1)的Dyck路径数可以由加泰罗尼亚语数C(n)给出。
我们强烈建议您单击此处并进行实践,然后再继续解决方案。
以下是查找Dyck路径(或第n个加泰罗尼亚语编号)的计数的实现。
C++
// C++ program to count
// number of Dyck Paths
#include
using namespace std;
// Returns count Dyck
// paths in n x n grid
int countDyckPaths(unsigned int n)
{
// Compute 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
int main()
{
int n = 4;
cout << "Number of Dyck Paths is "
<< countDyckPaths(n);
return 0;
}
Java
// Java program to count
// number of Dyck Paths
class GFG
{
// Returns count Dyck
// paths in n x n grid
public static int countDyckPaths(int n)
{
// Compute 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 = 4;
System.out.println("Number of Dyck Paths is " +
countDyckPaths(n));
}
}
Python3
# Python3 program to count
# number of Dyck Paths
# Returns count Dyck
# paths in n x n grid
def countDyckPaths(n):
# Compute value of 2nCn
res = 1
for i in range(0, n):
res *= (2 * n - i)
res /= (i + 1)
# return 2nCn/(n+1)
return res / (n+1)
# Driver Code
n = 4
print("Number of Dyck Paths is ",
str(int(countDyckPaths(n))))
# This code is contributed by
# Prasad Kshirsagar
C#
// C# program to count
// number of Dyck Paths
using System;
class GFG {
// Returns count Dyck
// paths in n x n grid
static int countDyckPaths(int n)
{
// Compute 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 = 4;
Console.WriteLine("Number of "
+ "Dyck Paths is " +
countDyckPaths(n));
}
}
// This code is contributed by anuj_67.
PHP
Javascript
输出 :
Number of Dyck Paths is 14
锻炼 :
- 找到1和-1的序列数,使每个序列遵循以下约束:
a)序列的长度为2n
b)1和-1的个数相等,即n 1个,n -1个
c)每个序列的前缀总和大于或等于0。例如,1,-1,1,-1和1,1,-1,-1是有效的,但是-1,-1,1, 1无效。 - 从(m-1,0)到(0,n-1)的长度为m + n的路径数,仅限于东和北台阶。