1. 程式人生 > 實用技巧 >leetcode刷題筆記一百一十八題 楊輝三角

leetcode刷題筆記一百一十八題 楊輝三角

leetcode刷題筆記一百一十八題 楊輝三角

源地址:118. 楊輝三角

問題描述:

給定一個非負整數 numRows,生成楊輝三角的前 numRows

在楊輝三角中,每個數是它左上方和右上方的數的和。

示例:

輸入: 5
輸出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

/**
本題也屬於動態規劃問題,在次對角線的三角形內計算
狀態轉換方程: below(i+1) = upper(i) + upper(i+1)
*/
import scala.collection.mutable
object Solution {
    def generate(numRows: Int): List[List[Int]] = {
        if (numRows == 0) return List.empty
        if (numRows == 1) return List(List(1))
        if (numRows == 2) return List(List(1), List(1, 1))

        val res = mutable.ListBuffer[List[Int]]()
        res += List(1)
        res += List(1, 1)

        val length = numRows - 2
        for (i <- 0 until length) res += next(res.last)

        return res.toList 
    }

    def next(l: List[Int]): List[Int] = {
        var r = Array.fill[Int](l.length+1)(1)
        r(0) = 1
        r(r.length-1) = 1
        for(i <- 0 to l.length-2) r(i+1) = l(i) + l(i+1)
        return r.toList
    }
}