【Leetcode】Pascal's Triangle II

2023-06-14,,

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?

思路:最简单的方法就是依照【Leetcode】Pascal's
Triangle 的方式自顶向下依次求解,但会造成空间的浪费。若仅仅用一个vector存储结果。在下标从小到大的遍历过程中会改变vector的值,如[1, 2, 1] 按小标从小到大累计会变成[1, 3, 4, 1]不是所求解,因此能够採取两种解决方法,简单的一种则是使用两个vector,一个存上一层的值。一个存本层的值,然后再进行交换。第二种方法则是按下标从大到小进行遍历,则会避免上述问题。

class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> result; for(int i = 0; i <= rowIndex; i++)
{
for(int j = i - 1; j > 0; j--)
result[j] = result[j] + result[j - 1]; result.push_back(1);
} return result;
}
};

【Leetcode】Pascal's Triangle II的相关教程结束。

《【Leetcode】Pascal's Triangle II.doc》

下载本文的Word格式文档,以方便收藏与打印。