算法(TS):杨辉三角

569 阅读1分钟

给定一个非负整数 numRows, 生成「杨辉三角」的前 numRows 行。在杨辉三角中,每个数都是其左上角和右上角的和

示例 1:

输入: numRows = 5

输出: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

示例 2:

输入: numRows = 1

输出: [[1]]

提示: 1 <= numRows <= 30

解法

第一行固定为[1],第二行固定为[1,1],其余行中每个数的计算公式为 (prevRow[j] || 0) + (prevRow[j-1] || 0),第1行1个数,第2行2个数,第3行3个数,以此类推。

function generate(numRows: number): number[][] {
    const res = []
    
    for(let i = 0; i < numRows; i++) {
        if(i===0) {
            res.push([1])
            continue
        }
        if(i === 1) {
            res.push([1,1])
            continue
        }

        const nums: number[] = []
        const prevRow = res[i-1]
        for(let j = 0; j < i + 1; j++) {
            nums.push((prevRow[j] || 0) + (prevRow[j-1] || 0))
        }

        res.push(nums)
    }
    return res
};

时间复杂度O(numRows*numRows),空间负责度O(1)