-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path118. Pascal's Triangle.cpp
60 lines (47 loc) · 1.25 KB
/
118. Pascal's Triangle.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
/*
Link: https://leetcode.com/problems/pascals-triangle/
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
*/
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> ans;
if (numRows == 0) {
return ans;
}
vector<int>v; // sub vector
v.push_back(1); // first row
ans.push_back(v); // inserting sub vector in ans
if (numRows == 1) {
return ans;
}
v.push_back(1);
ans.push_back(v);
int i, j;
for (i = 1; i < numRows - 1; i++) {
v.clear();
v.push_back(1);
for(j = 1; j < ans[i].size(); j++) {
v.push_back(ans[i][j-1] + ans[i][j]); // creating the next subsequent row
}
v.push_back(1);
ans.push_back(v);
}
return ans;
}
};
/*
TC = O(n ^ 2)
SC = O(n ^ 2)
*/