Catalan numbers satisfy the following recursive formula.
Catalan numbers are a sequence of natural numbers that occurs in many interesting counting problems like following.
Program for nth Catalan Number - GeeksforGeeks
Program for nth Catalan Number - GeeksforGeeks
https://www.youtube.com/watch?v=eUw9A1wsFg8&ab_channel=Pepcoding
C(n, k)
= n! / (n-k)! * k!
= [n * (n-1) *....* 1] / [ ( (n-k) * (n-k-1) * .... * 1) *
( k * (k-1) * .... * 1 ) ]
After simplifying, we get
C(n, k)
= [n * (n-1) * .... * (n-k+1)] / [k * (k-1) * .... * 1]
Also, C(n, k) = C(n, n-k)
// r can be changed to n-r if r > n-r
DP based solution
#include <iostream>
using namespace std;
// A dynamic programming based function to find nth
// Catalan number
unsigned long int catalanDP(unsigned int n)
{
// Table to store results of subproblems
unsigned long int catalan[n + 1];
// Initialize first two values in table
catalan[0] = catalan[1] = 1;
// Fill entries in catalan[] using recursive formula
for (int i = 2; i <= n; i++) {
catalan[i] = 0;
for (int j = 0; j < i; j++)
catalan[i] += catalan[j] * catalan[i - j - 1];
}
// Return last entry
return catalan[n];
}
// Driver code
int main()
{
for (int i = 0; i < 10; i++)
cout << catalanDP(i) << " ";
return 0;
}
// Time complexity : O(n^2)