Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function pascals_triangle($n) {
- // Your code here
- $firstRow = [1];
- $secondRow = [1,1];
- $rows = [
- 1 => $firstRow,
- 2 => $secondRow
- ];
- // when n is 1 or 2, return rowOne or rowTwo
- if ($n == 1) {
- return $rows[1];
- }
- if ($n == 2) {
- return array_merge($firstRow, $secondRow);
- }
- for ($row = 3; $row <= $n; $row++) {
- $prev = $rows[$row-1];
- // start is always 1
- $currentRow = [1];
- for ($i = 1; $i < $row - 1; $i++) {
- // current num
- $currentNum = $prev[$i - 1] + $prev[$i];
- $currentRow[] = $currentNum;
- }
- // add the end
- $currentRow[] = 1;
- $rows[] = $currentRow;
- }
- $result = [];
- foreach ($rows as $row) {
- $result = array_merge($result, $row);
- }
- return $result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement