119 Pascal's Triangle II

给定非负索引k,k <= 33,返回杨辉三角的第 k 行。

两个数组进行判断,时间复杂度O(n^2),空间复杂度O(n)

  • Runtime: 80 ms, faster than 53.02%
  • Memory Usage: 38.2 MB, less than 95.66%
/**
 * @param {number} rowIndex
 * @return {number[]}
 */
var getRow = function(rowIndex) {
    var pre = [1]
    var cur = [1]
    if(rowIndex === 0) return pre
    while(cur.length <= rowIndex){
        for(var i = 1; i < pre.length; i++){
            cur[i] = pre[i - 1] + pre[i]
        }
        cur.push(1)
        pre = cur.slice()
    }
    return cur
};

单个数组进行判断

  • Runtime: 76 ms, faster than 79.22%
  • Memory Usage: 38.6 MB, less than 41.55%
/**
 * @param {number} rowIndex
 * @return {number[]}
 */
var getRow = function(rowIndex) {
    let res = Array(rowIndex + 1).fill(0)
    res[0] = 1
    for(let i = 1; i <= rowIndex; i++) {
        for(let j = i; j > 0; j--) {
            res[j] += res[j - 1]
        }
    }
    return res
};

你可能感兴趣的:(119 Pascal's Triangle II)