119. Pascal’s Triangle II
一、问题描述
Given an index k, return the *k*th row of the Pascal’s triangle.
Could you optimize your algorithm to use only O(k) extra space?
二、输入输出
For example, given k = 3,
Return [1,3,3,1]
.
三、解题思路
递归解法
- 要求空间复杂度为o(k) 是本题的难点,想要从头一点点遍历来产生怕是不行了
- 像这种按照一定的规律来产生数组的,可以考虑使用递归
- 递归调用自己产生
第k-1行
的结果,根据这个结果可以产生第k行
的结果 - 退出条件设置为rowIndex为0或者1
class Solution {
public:
vector<int> getRow(int rowIndex) {
if(rowIndex <= 0) return vector<int>(1,1);
if(rowIndex == 1) return vector<int>(2, 1);
vector<int> lastLine = getRow(rowIndex - 1);
vector<int> ret;
ret.push_back(1);
for (int i = 1; i <= (rowIndex-1); ++i) {
ret.push_back(lastLine[i - 1] + lastLine[i]);
}
ret.push_back(1);
return ret;
}
};