Catalan numbers are a sequence of natural numbers that occurs in many interesting counting problems like following.
1) Count the number of expressions containing n pairs of parentheses which are correctly matched. For n = 3, possible expressions are ((())), ()(()), ()()(), (())(), (()()).
2) Count the number of possible Binary Search Trees with n keys
3) Count the number of full binary trees (A rooted binary tree is full if every vertex has either two children or no children) with n+1 leaves.
4) Given a number n, return the number of ways you can draw n chords in a circle with 2 x n points such that no 2 chords intersect.
The first few Catalan numbers for n = 0, 1, 2, 3, %u2026 are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, %u2026
Recursive Solution
Catalan numbers satisfy the following recursive formula.
Following is the implementation of above recursive formula.
1 1 2 5 14 42 132 429 1430 4862
Time complexity of above implementation is equivalent to nth catalan number.
The value of nth catalan number is exponential that makes the time complexity exponential.
Dynamic Programming Solution : We can observe that the above recursive implementation does a lot of repeated work (we can the same by drawing recursion tree). Since there are overlapping subproblems, we can use dynamic programming for this. Following is a Dynamic programming based implementation .
1 1 2 5 14 42 132 429 1430 4862
Time Complexity: Time complexity of above implementation is O(n2)
Using Binomial Coefficient
We can also use the below formula to find nth Catalan number in O(n) time.
We have discussed a O(n) approach to find binomial coefficient nCr.
1 1 2 5 14 42 132 429 1430 4862
Time Complexity: Time complexity of above implementation is O(n).
We can also use below formula to find nth catalan number in O(n) time.
Use multi-precision library: In this method, we have used boost multi-precision library, and the motive behind its use is just only to have precision meanwhile finding the large CATALAN%u2019s number and a generalized technique using for loop to calculate Catalan numbers .
For example: N = 5
Initially set cat_=1 then, print cat_ ,
then, iterate from i = 1 to i < 5
for i = 1; cat_ = cat_ * (4*1-2)=1*2=2
cat_ = cat_ / (i+1)=2/2 = 1For i = 2; cat_ = cat_ * (4*2-2)=1*6=6
cat_ = cat_ / (i+1)=6/3=2For i = 3 :- cat_ = cat_ * (4*3-2)=2*10=20
cat_ = cat_ / (i+1)=20/4=5For i = 4 :- cat_ = cat_ * (4*4-2)=5*14=70
cat_ = cat_ / (i+1)=70/5=14
Pseudocode:
a) initially set cat_=1 and print it
b) run a for loop i=1 to i<=n
cat_ *= (4*i-2)
cat_ /= (i+1)
print cat_
c) end loop and exit
- C++
1 1 2 5 14
Time Complexity: O(n)
Auxiliary Space: O(1)
Comments