-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram to generate Pascal's Triangle
More file actions
108 lines (86 loc) · 2.12 KB
/
Program to generate Pascal's Triangle
File metadata and controls
108 lines (86 loc) · 2.12 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
Approach 1 : In this case, we are given the row number r and the column number c, and we need to find out the element at position (r,c).
#include <bits/stdc++.h>
using namespace std;
int nCr(int n, int r) {
long long res = 1;
// calculating nCr:
for (int i = 0; i < r; i++) {
res = res * (n - i);
res = res / (i + 1);
}
return res;
}
int pascalTriangle(int r, int c) {
int element = nCr(r - 1, c - 1);
return element;
}
int main()
{
int r = 5; // row number
int c = 3; // col number
int element = pascalTriangle(r, c);
cout << "The element at position (r,c) is: "
<< element << "n";
return 0;
}
Aproach 2 : Given the row number n. Print the n-th row of Pascal’s triangle.
#include <bits/stdc++.h>
using namespace std;
int nCr(int n, int r) {
long long res = 1;
// calculating nCr:
for (int i = 0; i < r; i++) {
res = res * (n - i);
res = res / (i + 1);
}
return res;
}
void pascalTriangle(int n) {
// printing the entire row n:
for (int c = 1; c <= n; c++) {
cout << nCr(n - 1, c - 1) << " ";
}
cout << "n";
}
int main()
{
int n = 5;
pascalTriangle(n);
return 0;
}
Approch 3 : We will try to generate all the row elements by simply using the naive approach of variation 2.
#include <bits/stdc++.h>
using namespace std;
int nCr(int n, int r) {
long long res = 1;
// calculating nCr:
for (int i = 0; i < r; i++) {
res = res * (n - i);
res = res / (i + 1);
}
return (int)(res);
}
vector<vector<int>> pascalTriangle(int n) {
vector<vector<int>> ans;
//Store the entire pascal's triangle:
for (int row = 1; row <= n; row++) {
vector<int> tempLst; // temporary list
for (int col = 1; col <= row; col++) {
tempLst.push_back(nCr(row - 1, col - 1));
}
ans.push_back(tempLst);
}
return ans;
}
int main()
{
int n = 5;
vector<vector<int>> ans = pascalTriangle(n);
for (auto it : ans) {
for (auto ele : it) {
cout << ele << " ";
}
cout << "n";
}
return 0;
}