题目:
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?
翻译:
Pascal三角形,每一行的元素等于前一行相邻两个元素的和。返回第k行元素。
思路:
此题是118题的后续,重点在于需要用O(k)的空间复杂度。只需要使用一个记录前一行的整型vector,新的一行就是上一行相邻两两元素的和。
代码:
class Solution {
public:
vector getRow(int rowIndex) {
vector result;
vector temp;
for (int i=0;i=i)
{
result[j]=temp[j-1]+0;
}
else
{
result[j]=temp[j-1]+temp[j];
}
}
}
return result;
}
};
结果: