您的位置:首页 > 其它

[Leetcode] Pascal's Triangle II

2016-12-16 13:08 423 查看

描述

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?

分析

给定 n 返回杨辉三角的第 n 行。

仿照 前一题 [Pascal’s Triangle] 的思路进行构造。由于这里不需要返回前 n 行而只需要第 n 行,因此可以共用一个向量,每次将杨辉三角的下一行赋值给这个向量,直到第 n 行,这样空间复杂度为 0(n) 。

代码

class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> res(rowIndex + 1, 0);
for (int i = 0; i <= rowIndex; i++) {
res[0] = res[i] = 1;
for (int j = i - 1; j > 0; j--)
res[j] += res[j - 1];
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: