LN : leetcode 118 Pascal's Triangle
lc 118 Pascal's Triangle
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]
]
DP Accepted
这个问题就是杨辉三角,先初始化边界,再用递推式ans[i][j] = ans[i-1][j] + ans[i-1][j-1]递推即可得到答案。
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> ans(numRows);
if (numRows <= 0) return ans;
for (int i = 0; i < numRows; i++) ans[i].resize(i+1);
for (int i = 0; i < numRows; i++) ans[i][0] = ans[i][i] = 1;
for (int i = 2; i < numRows; i++)
for (int j = 1; j < i; j++)
ans[i][j] = ans[i-1][j] + ans[i-1][j-1];
return ans;
}
};