2 minutes
Leetcode 118
The idea of this solution is pretty simple:
- We first have a matrix array called
res - Then we loop through
numRows - While iterating through
numRowswe have to make an array calledtemp. It is going to be our current row. - We make
temp[0]andtemp[len(temp)]equal to1so we get the outer1’s. - Then we loop through the middle elements (basically excluding the outside
1’s) - We have to make every
temp[j]equal to the previous rowsprevious rows[j - 1] + previous rows[j]. We doj - 1andj. If you don’t understand, why look at the image below:
- Then we append
temptores - After iterating, we can return
res.
The Code:
func generate(numRows int) [][]int {
res := [][]int{}
for i := 0; i < numRows; i++ {
temp := make([]int, i+1)
temp[0], temp[len(temp)-1] = 1, 1
for j := 1; j < len(temp)-1; j++ {
temp[j] = res[i-1][j-1] + res[i-1][j]
}
res = append(res, temp)
}
return res
}
We can Take Out Temp And Get:
func generate(numRows int) [][]int {
res := [][]int{}
for i := 0; i < numRows; i++ {
res = append(res, make([]int, i+1))
res[i][0], res[i][len(res[i])-1] = 1, 1
for j := 1; j < len(res[i])-1; j++ {
res[i][j] = res[i-1][j-1] + res[i-1][j]
}
}
return res
}
Read other posts