杨辉三角

杨辉三角

描述:

给定一个非负整数 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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值