/
118.pascals-triangle.cpp
73 lines (66 loc) · 1.41 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
* @lc app=leetcode id=118 lang=cpp
*
* [118] Pascal's Triangle
*
* https://leetcode.com/problems/pascals-triangle/description/
*
* algorithms
* Easy (44.37%)
* Total Accepted: 228.1K
* Total Submissions: 512.4K
* Testcase Example: '5'
*
* 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) {
// 0. 边界判断
if (numRows == 0) {
return vector<vector<int>>(0);
}
// 1. 返回值
vector<vector<int>> result;
// 起始状态
vector<int> layer1(1,1);
result.push_back(layer1);
// 动态过程
for(int i = 1; i < numRows; i++)
{
vector<int> layer;
for(int j = 0; j <=i; j++)
{
if (j == 0 || j == i) {
layer.push_back(1);
}
else
{
layer.push_back(result[i-1][j-1] + result[i-1][j]);
}
}
result.push_back(layer);
}
return result;
}
};