-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPascal's_Triangle.C++
79 lines (65 loc) · 1.41 KB
/
Pascal's_Triangle.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
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
#include<bits/stdc++.h>
using namespace std;
//Pascals triangle
//Variation 1: Given row number r and column number c. Print the element at position (r, c) in Pascal’s triangle.
int nCr(int n,int r){
long long res = 1;
for(int i=0;i<r;i++){
res = res*(n-i);
res = res/(i+1);
}
return res;
}
//Variation 2: Given the row number n. Print the n-th row of Pascal’s triangle.
void pascal_row(int row){
for(int i=1;i<=row;i++){
cout<<nCr(row-1,i-1)<<" ";
}
cout<<endl;
}
//Variation 3: Given the number of rows n. Print the first n rows of Pascal’s triangle.
void pascal_triangle(int n){
for(int i=1;i<=n;i++){
pascal_row(i);
}
}
// Optimized Pascal triangle
vector<int> generate_rows(int n){
long long res =1;
vector<int>ans;
ans.push_back(1);
for(int i=1;i<n;i++){
res = res*(n-i);
res = res/i;
ans.push_back(res);
}
return ans;
}
vector<vector<int>> pascal_tri(int n){
vector<vector<int>> ans;
for(int i=1;i<=n;i++){
ans.push_back(generate_rows(i));
}
return ans;
}
int main(){
/*
int r,c;
cin>>r>>c;
int k =nCr(r-1,c-1);
cout<<k;
int row;
cin>>row;
pascal_row(row);
*/
int n;
cin>>n;
pascal_triangle(n);
vector<vector<int>> ans = pascal_tri(n);
for(auto it :ans){
for(auto ele :it){
cout<<ele<<" ";
}
cout<<endl;
}
}