欣迪
black and white modern building facade

出處: 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 行的值。

訂閱 IT-Monk

訂閱最新文章的發布消息! 😚😚😚
Loading

作者介紹 - 欣迪

欣迪

從設計到寫程式,發現自己有追求前端技巧的自虐傾向。不斷的踩坑,再從坑裡爬出來,慢慢對攀岩有點心得。 目前在多間公司擔任網站設計顧問。 同時也是網站架設公司負責人。