题目: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?
题目分析:
- 这道题目和第118题Pascal’s Triangle是类似题目,根据上一题的思路可求解;
- 唯一需要注意的是题目要求最终使用了额外的O(K)的空间,所以用从后往前的方法确定数组中的值
代码:
- C++:
class Solution {
public:
vector<int> getRow(int rowIndex)
{
vector<int> ans;
ans.push_back(1);
for(int i = 1;i <= rowIndex;i++)
{
for(int j = i; j > 0;j--)
{
if(j == i)
ans.push_back(1);
else
ans[j] = ans[j - 1] + ans[j];
}
}
return ans;
}
};