杨辉三角
描述:
给定一个非负整数 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/