A series of positive integers are known as Catalan numbers. They can be seen in various counting problems and are used to count permutations, particular lattice path kinds, etc.
Catalan numbers have the following recursive formula:
C0 = 0 and Cn+1 = Σ Ci Cn-i for n>=0 and n=>i>=0
The first few numbers of the Catalan number series are as follows:
n | Catalan Number |
---|---|
0 | 1 |
1 | 1 |
2 | 2 |
3 | 5 |
4 | 14 |
Given an integer n. Find the first n Catalan numbers.
Example 1:
Example 2:
We can use the following recursive formula to calculate the nth Catalan number:
C0 = 0 and Cn+1 = Σ Ci Cn-i for n>=0 and n=>i>=0
The steps to implement the recursive formula are as follows:
Define n
.
The base case is, if n
is less than or equal to 1
, it returns 1
.
The recursive step is where we return the sum of the product of i-th
Catalan number and n-i-1-th
Catalan number for all i
between 0 and n (0 inclusive).
Let’s look at the code below:
class Main {static int nthCatalanNum(int n) {int sum = 0;if(n<=1) return 1;for(int i=0; i<n; i++) {sum += nthCatalanNum(i) * nthCatalanNum(n-i-1);}return sum;}public static void main(String[] args) {int n=5;System.out.println("Catalan numbers upto " + n + " are as follows:");for (int i=0; i<n; i++) {System.out.print(nthCatalanNum(i) + " ");}}}
nthCatalan()
funtion.sum
and initialized it to zero.n
is less than or equal to 1
, then return 1
.for
loop to find the nth
Catalan number.n
.n
Catalan numbers.Free Resources