<p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;">Given an index <span style="box-sizing: border-box;">k</span>, return the <span style="box-sizing: border-box;">k</span><span style="box-sizing: border-box; position: relative; font-size: 12px; line-height: 0; vertical-align: baseline; top: -0.5em;">th</span> row of the Pascal's triangle.</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;">For example, given <span style="box-sizing: border-box;">k</span> = 3,<br style="box-sizing: border-box;" />Return <code style="box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 13px; padding: 2px 4px; color: rgb(199, 37, 78); background-color: rgb(249, 242, 244); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px;">[1,3,3,1]</code>.</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;"><span style="box-sizing: border-box; font-weight: 700;">Note:</span><br style="box-sizing: border-box;" />Could you optimize your algorithm to use only <span style="box-sizing: border-box;">O</span>(<span style="box-sizing: border-box;">k</span>) extra space?</p>
比较简单,就是考虑空间复杂度要求即可O(k):这里用到了vector<int> pre,cur;两个数组即可。
补充方法:可以将遍历顺序从后往前,并且只用一个数组。
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> ivCur;
if(rowIndex<0)
return ivCur;
else
{
vector<int> ivPre;
for(int row=0; row<=rowIndex; row++)
{
ivCur.push_back(1);
for(int col=1; col<row; col++)
{
ivCur.push_back(ivPre[col-1]+ivPre[col]);
}
if(row>0)
ivCur.push_back(1);
ivPre=ivCur;//记录下这次结果便于下回使用
ivCur.clear();//清空数组便于下回循环使用
}
return ivPre;
}
}
};