Problem:
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]
]
思路:
每一行由上一行产生,第一个和最后一个数为1,然后中间的数由上一行对应的数与它左边的数相加得到。也称为杨辉三角,在中国南宋数学家杨辉1261年所著的《详解九章算法》一书中出现,比欧洲的帕斯卡早了393年。
Solution:
vector<vector<int>> generate(int numRows) {
if (numRows == 0) return vector<vector<int>>{};
vector<vector<int>> res(1, {1});
for (int i = 1 ; i < numRows; i++) {
vector<int> ans(i+1);
ans[0] = ans[i] = 1;
for (int j = 1; j <= i-1; j++) {
ans[j] = res.back()[j-1] + res.back()[j];
}
res.push_back(ans);
}
return res;
}
性能:
Runtime: 0 ms Memory Usage: 8.8 MB