[LeetCode By Go 85]118. Pascal's Triangle

题目

Given numRows, generate the first numRows of Pascal’s triangle.

For example, given numRows = 5,
Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

解题思路

对于每一行,先找到前一半的数,右半边的数可以根据左右对称得到
对于每一行,有如下规律,

  1. 对于第row行,有row+1个数
  2. 第1个数triangele[row][0]为1
  3. 第i个数(i < row/2 + 1), 等于triangle[row-1][i-1] + triangle[row-1][i]
  4. 剩余的row/2个数( row/2 < i < row ), 可以根据左边的数得到

代码

func generate(numRows int) [][]int {
    var triangle [][]int
    if 0 == numRows {
        return triangle
    }
    triangle = append(triangle, []int{1})
    if 1 == numRows {
        return triangle
    }

    i := 1
    for ; i < numRows; i++ {
        var row []int
        row = append(row, 1)

        j := 1
        for ; j < i/2 + 1; j++ {
            tmp := triangle[i-1][j-1] + triangle[i-1][j]
            row = append(row, tmp)
        }
        
        j = (i-1)/2
        for ; j >=0; j-- {
            row = append(row, row[j])
        }
        fmt.Printf("row:%+v", row)
        
        triangle = append(triangle, row)
    }
    
    return triangle
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/280202419a48
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞