楊輝三角

楊輝三角

描述:

給定一個非負整數 numRows,生成楊輝三角的前 numRows 行。
楊輝三角
在楊輝三角中,每個數是它左上方和右上方的數的和。

分析:

通過在楊輝三角中,每個數是它左上方和右上方的數的和。可知:
第i行第j列的數:

$result[$i][$j] = $result[$i - 1][$j - 1] + $result[$i - 1][$j]

而第一列和每行最後一個數都爲1,第i行有且只有i列。

解答:

法1:

class Solution {

    /**
     * @param Integer $numRows
     * @return Integer[][]
     */
    function generate($numRows) {
        $result = [];
        for ($i = 0; $i < $numRows; $i++) {
            for ($j = 0; $j <= $i; $j++) {
                $result[$i][$j] = $this->_pascalNum($i, $j, $result);
            }
        }
        return $result;
    }

    /**
     * 計算第$row行第$col列的楊輝三角值
     * @param  Integer $row    [行]
     * @param  Integer $col    [列]
     * @param  Integer[][] $result [已經計算出來的楊輝三角值]
     * @return Integer         [第$row行第$col列的楊輝三角值]
     */
    private function _pascalNum($row, $col, $result) {
        if (isset($result[$row][$col])) { // 複用已經算出來的值
            return $result[$row][$col];
        }
        if ($col == 0 | $row == $col) {
            $result[$row][$col] = 1;
            return 1;
        }
        $result[$row][$col] = $this->_pascalNum($row - 1, $col - 1, $result) + $this->_pascalNum($row - 1, $col, $result);
        return $result[$row][$col];
    }
}

法2:

class Solution {

    /**
     * @param Integer $numRows
     * @return Integer[][]
     */
    function generate($numRows) {
        $result = [];
        for ($i = 0; $i < $numRows; $i++) {
            for ($j = 0; $j <= $i; $j++) {
                if ($j == 0 | $j == $i) {
                    $result[$i][$j] = 1;
                } else {
                    $result[$i][$j] = isset($result[$i - 1][$j]) ? ($result[$i - 1][$j - 1] + $result[$i - 1][$j]) : 1;
                }
            }
        }
        return $result;
    }
}

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/pascals-triangle/

發佈了28 篇原創文章 · 獲贊 20 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章