Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit bf98c83

Browse files
committed
杨辉三角
1 parent 11b37cd commit bf98c83

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

‎pascals_triangle/pascals_triangle.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<?php
2+
/**
3+
* pascals_triangle 以数组形式输出杨辉三角
4+
* Write a function that, given a depth (n), returns a single-dimensional array representing Pascal's Triangle to the n-th level.
5+
* @param [type] $n 几项
6+
* @return [array]
7+
*/
8+
function pascals_triangle($n)
9+
{
10+
// Your code here
11+
$orginArr = [1];
12+
if ($n == 1) return $orginArr;
13+
$tmp = $orginArr;
14+
array_push($orginArr, 1);
15+
$result = array_merge($tmp, $orginArr);
16+
if ($n == 2) return $result;
17+
$row = 2;
18+
// 循环$n大于2的情况
19+
while ($row <= $n - 1) {
20+
$oldArr = $orginArr;
21+
$orginArr[$row] = 1;
22+
$row++;
23+
for ($i = 1; $i < count($oldArr); $i++) {
24+
$orginArr[$i] = $oldArr[$i] + $oldArr[$i - 1];
25+
}
26+
$result = array_merge($result, $orginArr);
27+
}
28+
return $result;
29+
}
30+
// 以数组形式输出杨辉三角 聪明的办法
31+
function pascals_triangle_clever($n)
32+
{
33+
$pascal = [];
34+
for ($i = 0; $i < $n; $i++) {
35+
$num = 1;
36+
for ($j = 0; $j <= $i; $j++) {
37+
array_push($pascal, $num);
38+
$num = $num * ($i - $j) / ($j + 1);
39+
}
40+
}
41+
return $pascal;
42+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /