觀前提醒:
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
In 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
1 1
 \|
1 2 1
 \|\|
1 3 3 1
 \|\|\|
1 4 6 4 1
經我們重新整理此圖後,再搭配運算思維--抽象化的角度來嘗試找出通用的解釋:
任一列(n)裡面,第 k 個數字等於前一列(第 n-1 列)的第 k 個數字與第 k-1 個數字的和
一旦辨識出好的通則後,我們就可以著手開發演算法囉~
/**
 * @param {number} numRows
 * @return {number[][]}
 */
var generate = function (numRows) {
  // 處理 edge case
  if (numRows === 0) return [];
  // 初始狀態
  let triangle = [[1]];
  for (let i = 1; i < numRows; i++) {
    let prevRow = triangle[i - 1];
    // 每列最首位,一定為 1
    let currRow = [1];
    for (let j = 1; j < i; j++) {
      // 每列的第 n 個數值,皆為前一列 prevRow[j - 1] + prevRow[j] 之總和。
      let x = Number(prevRow[j - 1]);
      let y = Number(prevRow[j]);
      currRow.push([x + y]);
    }
    // 每列最末位,一定為 1
    currRow.push([1]);
    // 把處理好的 currRow ,push 進我們的 triangle
    triangle.push(currRow);
  }
  return triangle;
};
依照上面的思路,再搭配 CODE 內的註解,希望大家應該對於巴斯卡三角形,能有更多的認識~
謝謝大家的收看,LeetCode 小學堂我們下次見~