[LeetCode][JavaScript]Pascal's Triangle II

Pascal's Triangle II

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?

https://leetcode.com/problems/pascals-triangle-ii/

要求常数级的空间复杂度。

只维护一行的数据,每次从后往前算(因为每次是当前的值加上前一个的值,从后往前就不会影响结果),最后补上1。

 1 /**
 2  * @param {number} rowIndex
 3  * @return {number[]}
 4  */
 5 var getRow = function(rowIndex) {
 6     if(rowIndex === 0){
 7         return [1];
 8     }else if(rowIndex === 1){
 9         return [1, 1];
10     }
11 
12     var n = rowIndex - 1;
13     var row = [1, 1];
14     while(n--){
15         for(var i = row.length - 1; i >= 1; i--){
16             row[i] = row[i] + row[i - 1];
17         }
18         row.push(1);
19     }
20     return row;
21 };
 
原文地址:https://www.cnblogs.com/Liok3187/p/4842626.html