Skip to content

Latest commit

 

History

History
47 lines (42 loc) · 906 Bytes

118. 杨辉三角.md

File metadata and controls

47 lines (42 loc) · 906 Bytes

给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

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

solution:

/**
 * @param {number} numRows
 * @return {number[][]}
 */
var generate = function(numRows) {
    if (numRows === 0) return []
    let temp = 1
    let res = [[1]]
    while(temp < numRows) {
        console.log(temp)
        temp++
        if (temp === 2) {
            res.push([1, 1])
        } else {
            const last = res[res.length - 1]
            const current = [1]
            last.forEach((item, idx, self) => {
                self[idx + 1] !== undefined && (current.push(item + self[idx + 1]))
            })
            current.push(1)
            res.push(current)
        }
    }
    return res
};