首页 > 代码库 > LeetCode119 Pascal's Triangle II

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