118. Pascal's Triangle

解釋每一層每一個欄位的數字來歷

class Solution {

    /**
     * @param Integer $numRows
     * @return Integer[][]
     */
    function generate($numRows) {
        $result = [];
        for($depth = 0; $depth <= $numRows; $depth++) {
            for($index = 0; $index < $depth; $index++) {
                // 最左邊永遠是 1
                if ($index == 0) {
                    $result[$depth][0] = 1;
                } 
                // 上一層的前一個與同一個 index
                else {
                    $result[$depth][$index] = $result[$depth - 1][$index - 1] + ($result[$depth - 1][$index] ?? 0);
                }
            }
        }

        return $result;
    }
}

https://leetcode.com/problems/pascals-triangle/solutions/3593293/topic

Last updated