leetcode.cn/problems/pa…

解法一:迭代法
func generate(numRows int) [][]int {
res := make([][]int, 0)
if numRows == 0{
return res
}
res = append(res, []int{1})
for i:=1; i<numRows; i++{
prevRow := res[len(res)-1]
curRow := generateNextRow(prevRow)
res = append(res, curRow)
}
return res
}
func generateNextRow(prevRow []int) []int{
curRow := []int{1}
for i := 0; i<len(prevRow)-1; i++{
curRow = append(curRow, prevRow[i]+prevRow[i+1])
}
curRow = append(curRow, 1)
return curRow
}
解法二:递归
func generate(numRows int) [][]int {
return generateRecursive(numRows)
}
func generateRecursive(numRows int) [][]int {
if numRows == 1 {
triangle := [][]int{}
firstRow := []int{1}
triangle = append(triangle, firstRow)
return triangle
}
triangle := generateRecursive(numRows - 1)
bottomRow := triangle[len(triangle)-1]
newRow := []int{1}
for i := 0; i < len(bottomRow)-1; i++ {
newRow = append(newRow, bottomRow[i]+bottomRow[i+1])
}
newRow = append(newRow, 1)
triangle = append(triangle, newRow)
return triangle
}