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:
前几天做的动态规划题好难呜呜,做道水题找回自信~
状态转移方程
triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j]
边界条件
triangle[0][0] = triangle[i][0] = triangle[i][i] = 1
代码
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> triangle;
vector<int> temp;
for(int i = 0; i < numRows; i++)
{
temp.clear();
temp.push_back(1);
for(int j = 1; j < i; j++)
{
temp.push_back(triangle[i-1][j-1] + triangle[i-1][j]);
}
if(i != 0)
temp.push_back(1);
triangle.push_back(temp);
}
return triangle;
}
};