-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPascalsTriangle1.cpp
More file actions
108 lines (88 loc) · 1.95 KB
/
Copy pathPascalsTriangle1.cpp
File metadata and controls
108 lines (88 loc) · 1.95 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*
Program Name : Pascal's Triangle
Program Description : Given row number and column number , print the element at row and column of
Pascal's Triangle
1. Algorithm Used : Brute Force
Time Complexity : O(N log N)
Auxiliary Space Requirement : O(N)
Intuition
2. Algorithm Used : Better
Time Complexity : O(2N)
Auxiliary Space Requirement : O(1)
3. Algorithm Used : Optimal - Dutch National Flag Algorithm
Time Complexity : O(N)
Auxiliary Space Requirement : O(1)
*/
#include <iostream>
using namespace std;
int factorial(int n)
{
if(n == 0 || n == 1)
{
return 1;
}
int result = 1;
for(int i=n; i>=1; i--)
{
result *= i;
}
return result;
}
int nCr1(int n, int r)
{
return factorial(n)/(factorial(r)*factorial(n-r));
}
int nCr2(int n, int r)
{
long long res = 1;
for(int i=0; i<r; i++)
{
res *= (n-i);
res = res/(i+1);
}
return res;
}
/*
1. Algorithm Used : Brute Force
Time Complexity : O(2N)
Auxiliary Space Requirement : O(1)
Intuition : Let row = n, and col = r, the nth row and rth col element is given by (n-1) C (r-1)
*/
int pascalsTriangle1(int row, int col)
{
return nCr1(row-1, col-1);
}
/*
1. Algorithm Used : Better
Time Complexity : O(col)
Auxiliary Space Requirement : O(1)
Intuition : Let row = n, and col = r, the nth row and rth col element is given by (n-1) C (r-1)
In this we use better version of nCr function
*/
int pascalsTriangle2(int row, int col)
{
return nCr2(row-1, col-1);
}
void printPascalsTriangleRow(int row)
{
for(int c=1; c<=row; c++)
{
cout << nCr2(row-1, c-1) << ' ';
}
}
// void printPascalsTriangle(int n)
// {
// for(int i=1; i<=n; i++)
// {
// printPascalsTriangleRow(i);
// cout << endl;
// }
// }
int main()
{
int row = 8, col = 4;
// int n = 20, r = 5;
// cout << pascalsTriangle1(row, col);
// printPascalsTriangleRow(5);
return 0;
}