forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
catalan_number.c
47 lines (39 loc) · 975 Bytes
/
catalan_number.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
The Catalan numbers form a sequence of natural numbers that occur in various
counting problems, often involving recursively-defined objects.
Application in some combinatorial problems:
1.Number of correct bracket sequence consisting of n opening and n closing brackets.
2.The number of rooted full binary trees with n+1 leaves (vertices are not numbered). A rooted binary tree is full if every vertex has either two children or no children.
3.The number of ways to completely parenthesize n+1 factors.
*/
#include <stdio.h>
int catalan(int num)
{
if (num <= 1)
{
return 1;
}
int res = 0;
for (int i = 0; i < num; i++)
res += catalan(i) *catalan(num - i - 1);
return res;
}
int main()
{
int num;
printf("Enter Number: ");
scanf("%d", &num);
printf("\n");
for (int i = 1; i <= num; i++)
{
printf("%d ", catalan(i));
}
return 0;
}
/*
Sample input and output
Enter number: 7
1 2 5 14 42 132 429
time complexity: O(n^2)
space complexity: O(n)
*/