-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0118-Pascals_Triangle.cpp
More file actions
83 lines (73 loc) · 1.68 KB
/
0118-Pascals_Triangle.cpp
File metadata and controls
83 lines (73 loc) · 1.68 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
/*******************************************************************************
* 0118-Pascals_Triangle.cpp
* Billy.Ljm
* 08 September 2023
*
* =======
* Problem
* =======
* https://leetcode.com/problems/pascals-triangle/
*
* Given an integer numRows, return the first numRows of Pascal's triangle.
*
* ===========
* My Approach
* ===========
* We'll just compute the rows one by one.
*
* This has a time complexity of O(n^2), and a space complexity of O(1), where
* n is the number of rows to be generated.
******************************************************************************/
#include <iostream>
#include <vector>
using namespace std;
/**
* << operator for vectors
*/
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
os << "[";
for (const auto elem : v) {
os << elem << ",";
}
if (v.size() > 0) os << "\b";
os << "]";
return os;
}
/**
* Solution
*/
class Solution {
public:
vector<vector<int>> generate(int numRows) {
// init first row
vector<vector<int>> out = vector<vector<int>>(numRows);
out[0] = { 1 };
// generate rows
for (int i = 1; i < numRows; i++) {
out[i] = vector<int>(out[i - 1].size() + 1, 1);
for (int j = 1; j < out[i - 1].size(); j++) {
out[i][j] = out[i - 1][j];
out[i][j] = out[i][j] + out[i - 1][j - 1];
}
}
// return
return out;
}
};
/**
* Test cases
*/
int main(void) {
Solution sol;
int numRows;
// test case 1
numRows = 5;
std::cout << "generate(" << numRows << ") = ";
std::cout << sol.generate(numRows) << std::endl;
// test case 2
numRows = 1;
std::cout << "generate(" << numRows << ") = ";
std::cout << sol.generate(numRows) << std::endl;
return 0;
}