php 楊輝三角

<?php
/*          1(1,1)(x,y)
          1(2,1)   1(2,2)
        1(3,1)   2(3,2)   1(3,3)
      1(4,1)   3(4,2)   3(4,3)   1(4,4)
    1   4   6   4   1
  1   5   10  10  5   1*/



function yanghui($line)
{
  $a = array();
  for($x = 1;$x <= $line;$x++)
  {
      for($y = 1;$y <= $x; $y++)
      {
          if($x == $y) $a[$x][$y] = 1;
          elseif($y == 1) $a[$x][$y] = 1;
          else $a[$x][$y] = $a[$x-1][$y-1] + $a[$x-1][$y];
      }
  }
  foreach($a as $k => $v)
  {
    echo str_repeat('&nbsp;',$line-$k).implode('&nbsp',$v).'<br />';
  }
}
yanghui(4);
相關文章
相關標籤/搜索