Pascal‘s Triangle II
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?
解题思路:
题目要求空间复杂度为O(k),我们只需记录上一层的记录即可。这里的k从0开始计数。
class Solution {
public:
vector<int> getRow(int rowIndex) {
if(rowIndex<0){
return vector<int>();
}
vector<int> result;
result.push_back(1);
for(int i = 1; i< rowIndex + 1; i++){ //第i行
vector<int> lastRow = result;
result.resize(i+1);
for(int j=0; j<i+1; j++){ //第i行第j个数
if(j==0||j==i){
result[j]=1;
}else{
result[j] = lastRow[j-1]+lastRow[j];
}
}
}
return result;
}
};[LeetCode] Pascal's Triangle II
原文地址:http://blog.csdn.net/kangrydotnet/article/details/45669281