LeetCode119 Pascal's Triangle II

Posted wangxiaobao的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode119 Pascal's Triangle II相关的知识,希望对你有一定的参考价值。

Given an index k, return the kth row of the Pascal‘s triangle. (Easy)

For example, given k = 3,
Return [1,3,3,1].

Note:
Could you optimize your algorithm to use only O(k) extra space?

 

分析:

上一题的followup,注意只能开O(k)的空间,实际上就是利用滚动数组的解法,每一行只与其上一行有关。

代码:

 1 class Solution {
 2 long long factorial(int n) {
 3     long long result = 1;
 4     for (int i = 1; i <= n; ++i) {
 5         result *= i;
 6     }
 7     return result;
 8 }
 9 public:
10     vector<int> getRow(int rowIndex) {
11         vector<int> result{1};
12         vector<int> oldVec;
13         for (int i = 2; i <= rowIndex + 1; ++i) {
14             result.push_back(1);
15             oldVec = result;
16             for (int j = 1; j < i - 1; ++j) {
17                 result[j] = oldVec[j - 1] + oldVec[j];
18             }
19         }
20         return result;
21     }
22 };

 



以上是关于LeetCode119 Pascal's Triangle II的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 119. Pascal's Triangle II

LeetCode 119. Pascal's Triangle II

C#解leetcode:119. Pascal's Triangle II

Java [Leetcode 119]Pascal's Triangle II

#Leetcode# 119. Pascal's Triangle II

LeetCode 119 Pascal's Triangle II