Given an index k, return the k th 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);因此採用的方法是隻使用一個定長的數組,用於存儲每一行的元素值,對於每個新的行,可對原先存放的行從後往前掃描,主要分爲以下三種情況;
最後一個元素,直接等於1、對於下標爲i的中間元素,有result[i]=result[i-1]+result[i];
最後一個元素,直接等於1;
class Solution
{
public:
vector<int> getRow(int rowIndex)
{
vector<int> result(rowIndex+1, 0);
result[0] = 1;
for (int i=1; i<rowIndex+1; i++)
{
for (int j=i; j>=1; j--)
{
result[j] += result[j-1];
}
}
return result;
}
};