118. Pascal's 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]
]
思路
该题比较简单,杨辉三角形,从第三行开始,除了首尾,中间元素的值可通过如下公式计算:cur[i] = prev[i] + prev[i-1]
计算当前行实现要点如下:
- 拷贝上一行,并在末尾添加元素1
- 倒着开始计算,i 不包括首尾,
cur[i] += cur[i-1]
C++11
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> res;
for (auto i = 0; i < numRows; ++i) {
vector<int> row;
if (!res.empty())
row.assign(res.at(i-1).begin(), res.at(i-1).end());
row.emplace_back(1);
for (auto j = i - 1; j > 0; --j)
row[j] += row[j-1];
res.emplace_back(row);
}
return res;
}
};
update 2019.03.07
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> res;
if (!numRows) return res;
res = {{1}};
for (int i = 1; i < numRows; i++) {
vector<int> row;
row.assign(res.at(i-1).begin(), res.at(i-1).end());
row.emplace_back(1);
for (int j = row.size() - 2; j > 0; j--) {
row[j] += row[j-1];
}
res.emplace_back(row);
}
return res;
}
};
ac结果:
Runtime: 4 ms, faster than 100.00% of C++ online submissions for Pascal's Triangle.
Memory Usage: 8.9 MB, less than 24.64% of C++ online submissions for Pascal's Triangle.
内存使用有点高,后面再来想办法改进一下。