-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
利用二维数组打印杨辉三角
- Loading branch information
Wang Shurong
committed
May 17, 2015
1 parent
e490fe5
commit b29e3fe
Showing
1 changed file
with
35 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
<?php | ||
//杨辉三角 | ||
|
||
/* | ||
思路分析: | ||
1. 需两层循环,外层循环控层数,内部两个循环,分别控制空格和数字 | ||
2. 内部第一个循环控制空格数(空格数=总层数-当前层数),空格打印数量递减 | ||
3. 内部第二个循环控制数字数(数字数=当前层数),数字打印数量递增 | ||
*/ | ||
function YangHui($n){ | ||
$arr = array(); | ||
// $x 层数 | ||
for($x=0; $x<$n; $x++){ | ||
// 空格数 = 总层数 - 当前层数 | ||
for($y=$x; $y<$n; $y++){ | ||
echo ' '; | ||
} | ||
|
||
// 数字数 = 当前层数 | ||
for($y=0; $y<=$x; $y++){ | ||
//每一行的首元素和尾元素恒为1 | ||
if($y==0 || $y==$x){ | ||
$arr[$x][$y] = 1; | ||
}else{ | ||
$arr[$x][$y] = $arr[$x-1][$y-1] + $arr[$x-1][$y]; | ||
} | ||
echo $arr[$x][$y],' '; | ||
} | ||
|
||
// 别忘了换行 | ||
echo '<br/>'; | ||
} | ||
} | ||
YangHui(5); | ||
?> |