-
Notifications
You must be signed in to change notification settings - Fork 1
/
118_Pascals_Triangle.cpp
52 lines (42 loc) · 1.03 KB
/
118_Pascals_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
// https://leetcode.com/problems/pascals-triangle/
// https://leetcode.com/problems/pascals-triangle/discuss/3346150/C%2B%2BJava-Super-Clean-and-Understandable-Code
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> generate(int numRows)
{
vector<vector<int>> list;
for (int i = 0; i < numRows; ++i)
{
vector<int> arr;
for (int j = 0; j < i + 1; ++j)
{
if (j == 0 || j == i)
{ // both ends
arr.push_back(1);
}
else
{ // middle
int upperLeft = list[i - 1][j - 1];
int upperRight = list[i - 1][j];
arr.push_back(upperLeft + upperRight);
}
}
list.push_back(arr);
}
return list;
}
int main()
{
int numRows = 5;
vector<vector<int>> list = generate(numRows);
for (vector<int> &arr : list)
{
for (int &i : arr)
{
cout << i << " ";
}
cout << "\n";
}
return 0;
}