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的follow-up。不同之处在于,给定一个k,只让输出第k行。虽然Leetcode标的仍然是easy,但对于我个人来讲,感觉要稍微难一些。思路仍然是首先定义一个vector,同时就用rowIndex + 1个1 来填满它。接下来,用一个二层for循环,第一层是i从第i = 0行开始往第rowIndex行遍历,第二层是对当年的第i行的每一个元素j从后往前反向进行update,具体的update方法是res[j] = res[j] + res [j - 1]。最后,返回res这个vector即可。
(这种思路我第一次也觉得比较难理解,所以这种方法的代码下面还有第二种与之类似但是比较容易理解的代码)
代码如下:
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> res(rowIndex + 1, 1);
for(int i = 0; i < rowIndex; ++i){
for(int j = i; j > 0; --j){
res[j] = res[j] + res[j - 1];
}
}
return res;
}
};
第二种与之类似但是比较容易理解的代码在这里:
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> res(1, 1);
for(int i = 0; i < rowIndex; ++i){
res.insert(res.begin(), 1);
for(int j = 1; j < res.size() - 1; ++j){
res[j] = res[j] + res[j + 1];
}
}
return res;
}
};

本文介绍了一种高效算法,用于计算帕斯卡三角形的第K行,通过优化算法实现仅使用O(k)额外空间的目标。该算法利用了两层for循环,巧妙地更新每一行的元素。
881

被折叠的 条评论
为什么被折叠?



