File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments