leetcode解题: Pascal's Triangle (118)

Given numRows, generate the first numRows of Pascal’s triangle.

For example, given numRows = 5,
Return

[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

解法1: O(N^2) N 是numRows

很基础的题,注意第i层的第j个字符是第i-1层的第j个数和第j-1个数之和就可以了。
C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> res;
if (numRows == 0) {
return res;
}
vector<int> x{1};
res.push_back(x);
for (int i = 1; i < numRows; ++i) {
vector<int> temp{1};
for (int j = 1; j < i; ++j) {
temp.push_back(res[i - 1][j - 1] + res[i - 1][j]);
}
temp.push_back(1);
res.push_back(temp);
}
return res;
}
};

Java

1