<p style="text-align: center;"><br/></p><p style="text-align: center;"><img src="/upload/content/20190312/1552320338417038.jpg" alt="PHP实现杨辉三角代码实例" title="PHP实现杨辉三角代码实例" width="550px"/></p><p>本文实例讲述了PHP实现的杨辉三角求解算法。分享给大家供大家参考,具体如下:<br/></p><p><strong>前言</strong></p><p>杨辉三角,是二项式系数在三角形中的一种几何排列。在欧洲,这个表叫做帕斯卡三角形。帕斯卡(1623—-1662)是在1654年发现这一规律的,比杨辉要迟393年,比贾宪迟600年。杨辉三角是中国古代数学的杰出研究成果之一,它把二项式系数图形化,把组合数内在的一些代数性质直观地从图形中体现出来,是一种离散型的数与形的结合。<a href="https://files.jb51.net/file_images/article/201903/2019311114817802.jpg?2019211114849" target="_blank"></a></p><p><strong>代码实现</strong></p><ul class=" list-paddingleft-2" style="list-style-type: disc;"><li><p>题目的要求是:设计代码,实现打印 杨辉三角 的功能</p></li><li><p>此处提供的参考代码为 PHP,其他语言可参考推敲</p></li></ul><p><strong>第一种方法</strong></p><p>使用两个 for 循环进行输出,比较好理解</p><pre class="brush:php;toolbar:false">/** * 第一种代码实现 * @param int $n 要求的层数 * 理解思路: $i代表行数; $j代表列数 */ public function funYH($n = 1){ //初始化数组 $arr = []; for($i = 0;$i < $n;$i++){ //注意循环条件 for($j = 0;$j <= $i;$j++){ if($j == 0 || $i == $j){ $arr[$i][$j] = 1; }else { $arr[$i][$j] = $arr[$i-1][$j-1]+$arr[$i-1][$j]; } echo $arr[$i][$j]."\t"; } echo "<br/>"; } }</pre><p><strong>第二种方法</strong></p><p>使用的是 while 循环</p><pre class="brush:php;toolbar:false;">/** * 第二种代码实现 * @param int $n 要求的层数 */ public function funYH2($n = 1){ //初始化数组 $arrL = [1,1]; //初始化索引 $index = 0; while ($index < $n){ if ($index == 0){ echo $arrL[$index]."\t"; }elseif ($index == 1){ echo $arrL[$index - 1]."\t".$arrL[$index]."\t"; }else{ $oldL = $arrL; for ($i = 0;$i <= count($oldL);$i++){ $arrL[$i] = $oldL[$i-1] + $oldL[$i]; echo $arrL[$i]."\t"; } } $index ++; echo "<br/>"; } }</pre><p><strong>输出结果</strong></p><p>输出的结果是相同的,参考如下:</p><p style="text-align: center;"><img src="/upload/content/20190312/1552320289373348.png" alt="PHP实现杨辉三角代码实例" title="PHP实现杨辉三角代码实例" width="550px"/></p><p>以上就是关于“PHP实现杨辉三角代码实例”的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流。</p>