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
    }
}
原文地址:https://www.cnblogs.com/ganshuoos/p/13458499.html