-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path119. Pascal's Triangle II.cpp
129 lines (88 loc) · 2.14 KB
/
119. Pascal's Triangle II.cpp
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.
Note that the row index starts from 0.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 3
Output: [1,3,3,1]
Follow up:
Could you optimize your algorithm to use only O(k) extra space?
class Solution {
public:
int gcdd(int a, int b){
if(b==0) return a;
return gcdd(b, a%b);
}
int NCR(int n, int r){
if(n==0) return 1;
if(r==0) return 1;
if(n-r<r) r=n-r;
long long p=1, k=1;
while(r){
p*=n;
k*=r;
int gcd=gcdd(p, k);
p/=gcd;
k/=gcd;
n--;
r--;
}
return p/k;
}
vector<int> getRow(int n) { // works fine till n<=33
vector<int> res;
for(int i=0;i<=n;i++){
int val=NCR(n, i);
res.push_back(val);
}
return res;
}
};
// using optimized ncr
class Solution {
public:
int NCR(int n, int r){
if(n==0 || r==0) return 1;
if(n-r<r) r=n-r;
long long p=1;
for(int i=1;i<=r;i++){
p*=n;
p/=i;
n--;
}
return p;
}
vector<int> getRow(int rowIndex) {
vector<int> res;
for(int i=0;i<=rowIndex;i++){
res.push_back(NCR(rowIndex, i));
}
return res;
}
};
// using ncr (better)
// NCr = (NCr - 1 * (N - r + 1)) / r where 1 = r = N
class Solution {
public:
vector<int> getRow(int n) {
vector <int> res(n + 1);
res[0] = 1; // nC0 = 1
for (int i = 1; i <= n; i++) {
res[i] = ((long long)res[i - 1] * (n - i + 1)) / i;
}
return res;
}
};
// Using O(n) space
class Solution {
public:
vector<int> getRow(int n) {
vector <int> res(n + 1, 0);
res[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = i; j >= 1; j--) {
res[j] += res[j - 1];
}
}
return res;
}
};