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?
题意:返回杨辉三角的第k行元素。要求只能使用O(k)的空间。
思路:从后向前依次迭代出当前行数组的数据,对原有的数组数据(向后错开一位)进行覆盖。
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> m(rowIndex+1, 1);
for (int i = 2; i <= rowIndex; i++){
for (int j = i - 1; j > 0; j--){
m[j] += m[j - 1];
}
}
return m;
}
};