LeetCode 118. Pascal’s Triangle
Given an integer numRows, return the first numRows of Pascal’s triangle.
In Pascal’s triangle, each number is the sum of the two numbers directly above it as shown:
Example 1:
Input: numRows = 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
method
状态转换方程:dp[i][j] = dp[i-1][j] + dp[i-1][j-1]
使用滚动数组,每次i
循环都在dp
后面插入一个1
,第一个1
和最后一个1
不用处理
只要处理dp
中间部分就可以了,注意要从后往前
vector<vector<int>> generate(int numRows) {
vector<vector<int>> res;
vector<int> dp;
for (int i = 0; i < numRows; i++) {
dp.push_back(1);
for (int j = i - 1; j > 0; j--) { // 从后往前处理
dp[j] += dp[j - 1];
}
res.push_back(dp);
}
return res;
}
LeetCode 119. Pascal’s Triangle II
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal’s triangle.
In Pascal’s triangle, each number is the sum of the two numbers directly above it as shown:
Example 1:
Input: rowIndex = 3
Output: [1,3,3,1]
method
vector<int> getRow(int rowIndex) {
vector<int> dp;
for (int i = 0; i <= rowIndex; i++) {
dp.push_back(1);
for (int j = i - 1; j > 0; j--) {
dp[j] += dp[j - 1];
}
}
return dp;
}