您的位置:首页 > 职场人生

86_leetcode_Pascal's Triangle II

2014-06-22 11:30 344 查看
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

1:分别考虑第一个元素,最后一个元素以及中间元素

vector<int> getRow(int rowIndex)
{
vector<int> result;
if(rowIndex < 0)
{
return result;
}
if(rowIndex == 0 )
{
result.push_back(1);
return result;
}

vector<int> temp;
for(int i = 1; i <= rowIndex; i++)
{
for(int j = 0; j <= i; j++)
{
if(j == 0 || j == i)
{
result.push_back(1);
}
else
{
result.push_back(temp[j-1] + temp[j]);
}
}
temp = result;
result.clear();
}

result = temp;
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息