<?php
/**
* 获取某行某列的值 (循环方式)
*
* @param $row 行数
* @param $col 列数
* @return number
*/
function getVal($row, $col)
{
if ($col > $row) {
return 0;
}
$tmp_arr = [];
for ($i=1; $i<=$row; $i++) {
for ($j=1; $j<=$col; $j++) {
if ($j == 1 || $j== $i) {
$tmp_arr[$i][$j] = 1;
} else {
$tmp_arr[$i][$j] = $tmp_arr[$i-1][$j] + $tmp_arr[$i-1][$j-1];
}
}
}
return $tmp_arr[$row][$col];
}
echo getVal(6,2);
/**
* 获取某行某列的值(递归方式)
*
* @param $row 行数
* @param $col 列数
* @return number
*/
function getVal2($row, $col)
{
if ($col > $row) {
return 0;
}
if ($col==1 || $col==$row) {
return 1;
} else {
return getVal2($row-1,$col-1) + getVal2($row-1,$col);
}
}
echo getVal2(6,2);
输入某行某列,返回其值,注意防止死递归(太简单了,丢人丢到家了)