Given an index k, return the kth 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?
內層循環,使用遞減方式。
因為計算當前值時,需要用到上一行的當前列和前一列。
如果從前向後的話,需要額外使用一個變量,來保存前一列的歷史值。
class Solution {
public:
vector getRow(int rowIndex) {
vector ans(rowIndex+1, 1);
for (int i=0; i<=rowIndex; i++) {
for (int j=i-1; j>0; j--) {
ans[j] += ans[j-1];
}
}
return ans;
}
};