问题描述
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] ]
解题思路
杨辉三角形的规律是,每一行的每一个值,等于其上一行中该值肩膀上抗的两个值,也就是C(n+1,i)=C(n,i)+C(n,i-1)
代码示例
class Solution {
public:
vector<vector<int> > generate(int numRows) {
vector<vector<int>> res;
for (int i = 0; i < numRows; i++) {
vector<int> temp(i + 1, 1);//初始化该行值为全1
for (int j = 1; j < i; j++) {
temp[j] = res[i - 1][j - 1] + res[i - 1][j];
}
res.push_back(temp);
}
return res;
}
};
问题描述
Given an index k, return the k th row of the Pascal's triangle.
For example, given k = 3,
Return[1,3,3,1].
Note:
Could you optimize your algorithm to use only O(k) extra space?
解题思路
要求额外空间复杂度为O(k),则不能采用上题方法,为保证下一行在更新时,前面的值不会被覆盖,则更改更新顺序,每次从最后面开始更新,这样不会提前覆盖掉前面的值。举个例子,
[ [1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1] ]
计算第五行时,从计算倒数第一个4开始,4 = 3 + 1,覆盖掉最后的1,但没有变3,继续计算6 = 3 + 3,覆盖掉3,但没有变前一个3,依次覆盖下去,该行即可更新完毕,且额外空间为O(k)
代码示例
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> res(rowIndex + 1, 1);
for(int i = 0; i < rowIndex + 1; i++) {
for(int j = i - 1; j > 0; j--) {
res[j] = res[j] + res[j - 1];
}
}
return res;
}
};