Description
Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.
In Pascal’s triangle, each number is the sum of the two numbers directly above it.
1 2 3 4 5 6 7 8 9
| Input: 5 Output: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
|
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| func generate(numRows int) [][]int { res := make([][]int, numRows)
for i := 0; i < numRows; i++ { res[i] = make([]int, i+1) res[i][0] = 1 res[i][i] = 1
for j := 1; j < i; j++ { res[i][j] = res[i-1][j-1] + res[i-1][j] } }
return res }
|
Note
假設有以下參數:
說明:
1 2 3 4 5 6 7
| 建立一個空的二維陣列:
[[], [], [], [], []]
將子陣列的頭尾設置為 1,並將中間元素設置為相應總和值。
最終返回:[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
|
Code