119. Pascal's Triangle II

class Solution {

    /**
     * @param Integer $rowIndex
     * @return Integer[]
     */
    function getRow($rowIndex) {
        $result = [];
        for($depth = 0; $depth <= $rowIndex + 1; $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[$rowIndex + 1];
    }
}

Last updated