zoukankan      html  css  js  c++  java
  • 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
        }
    }
    
  • 相关阅读:
    8.22
    webstrom安装流程
    8.21
    8.20
    8.20学习笔记
    使用WebClient异步获取http资源
    导航栏,可直接使用
    asp.net mvc5实现单点登录
    使用C#调用Word的接口生成doc文件与html文件
    下载网页并保存
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/13458499.html
Copyright © 2011-2022 走看看