出處: https://leetcode.com/problems/pascals-triangle-ii/
Given an integer rowIndex
, return the rowIndexth
(0-indexed) row of the Pascal’s triangle.
In Pascal’s triangle, each number is the sum of the two numbers directly above it as shown:
/** * @param {number} rowIndex * @return {number[]} */ var getRow = function(rowIndex) { function nextLayer(current) { const res = Array(current.length + 1).fill() res[0] = 1 res[res.length -1] = 1 for(let i = 0; i < current.length - 1; i++) { res[i+1] = current[i] + current[i+1] } return res } let current = [] for(i = 0; i <= rowIndex; i++) { current = nextLayer(current) } return current };
上面的代碼是包含一個內部函數 nextLayer,用於計算 Pascal’s Triangle 的下一行。 使用一個 current Array,並在 Array 上計算下一行,返回計算後的 Array。
最後,主函數使用 loop,調用 nextLayer 函數 rowIndex 次,以計算 Pascal’s Triangle 的第 rowIndex 行的值。