题目描述:
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.
Note that the row index starts from 0.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 3
Output: [1,3,3,1]
Follow up:
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> result(1,1);
if(rowIndex==0) return result;
else
{
for(int i=1;i<=rowIndex;i++)
{
result.insert(result.begin(),1);
for(int j=1;j<result.size()-1;j++)
result[j]=result[j]+result[j+1];
}
return result;
}
}
};