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;
}
};