題目
給定一個非負整數 numRows,生成楊輝三角的前 numRows 行。
在楊輝三角中,每個數是它左上方和右上方的數的和。
來源:https://leetcode-cn.com/problems/pascals-triangle/
輸入: 5
輸出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
解答
方法一:
我解答這個題目的時候分析是這樣的:
- 假設從row是從0 開始的
- 除row = 0 之外,所有的行兩邊的元素都是1
- 每行又 row + 1 個元素
- 每行除了 index = 0 index = row 之外的元素是上一行的 index - 1 和 index 的元素之和, row= 1 除外
因此構建每行的vector的時候,直接全部初始化爲1,然後再修改元素
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> res;
if (numRows >= 1) {
res.push_back({1}); //row 0
}
if (numRows >= 2) {
res.push_back({1,1}); //row 1
}
for (int row = 2; row < numRows; row++) {
vector<int> tmp(row + 1, 1); // 共有row + 1個元素
for (int col = 1; col < row; col++) {
///上一行的元素相加得到
tmp[col] = res[row - 1][col - 1] + res[row - 1][col];
}
///元素構建完成
res.push_back(std::move(tmp));
}
return res;
}
};