leetCode打卡——[118] Pascal's Triangle

198 阅读1分钟

题目

Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

n Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

Input: 5 Output:

[
 [1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

思路

  1. 如果我有一个已知的三角形,那么我就能为这个三角形多加一层,那么就是动态规划的思路;
  2. 当层数小于3的时候,是边界,可以直接返回结果;
  3. 可以用非递归的方式进行实现的。
var generate = function(numRows) {
    if (numRows === 0) return [];
    if (numRows === 1) return [[1]];
    if (numRows === 2) return [[1], [1, 1]]

    var res = [[1], [1, 1]];
    
    run(numRows - 2, res);

    return res;
};

var run = function(round, res) {
    if (!round) return;

    var row = [1];

    var lastRow = res[res.length - 1] || [];

    for (let i = 0; i < lastRow.length - 1; i++) {
        row.push(lastRow[i] + lastRow[i + 1]);
    }
    row.push(1);

    res.push(row);

    run(round - 1, res);
}