[LeetCode By Go 94]119. Pascal's Triangle II

题目

Given an index k, return the kth row of the Pascal’s triangle.

For example, given k = 3,
Return [1,3,3,1].

Note:
Could you optimize your algorithm to use only O(k) extra space?

解题思路

  1. 第一行:1
  2. 第二行:1,2
  3. 第row行:
    第一个数1,
    第i(1 < i <= row/2 +1)个数row[i] = preRow[i-1] + preRow[i],
    剩余的数等于前(row-1)/2个数的逆序

代码

func getRow(rowIndex int) []int {
    row := []int{1}

    if 0 == rowIndex {
        return row
    }
    row = append(row, 1)
    if 1 == rowIndex {
        return row
    }

    var newRow []int
    for i := 2; i <= rowIndex; i++ {
        newRow = []int{1}

        for j := 1; j < i/2 + 1; j++ {
            tmp := row[j-1] + row[j]
            newRow = append(newRow, tmp)
        }
        fmt.Printf("1newRow:%+v\n", newRow)
        for k := (i-1)/2; k >= 0; k-- {
            newRow = append(newRow, newRow[k])
        }
        fmt.Printf("2newRow:%+v\n", newRow)
        row = newRow
    }

    return row
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/2becbd859f69
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞