zoukankan      html  css  js  c++  java
  • leetcode刷题笔记一百一十九题 杨辉三角II

    leetcode刷题笔记一百一十九题 杨辉三角II

    源地址:119. 杨辉三角 II

    问题描述:

    给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。

    在杨辉三角中,每个数是它左上方和右上方的数的和。

    示例:

    输入: 3
    输出: [1,3,3,1]
    

    进阶:

    你可以优化你的算法到 O(k) 空间复杂度吗?

    /**
    本题中使用递归思想解决问题
    */
    object Solution {
        def getRow(rowIndex: Int): List[Int] = rowIndex match {
            case 0          => return List(1)
            case 1          => return List(1, 1)
            //对 n-1 的杨辉三角进行推理
            case n if n > 1 => return helper(getRow(n-1))
     	}
    	
        //由于杨辉三角具有对称性,本质上是从每行的末尾向左推理
        def helper(leftArr: List[Int], rightArr: List[Int] = List(1)): List[Int] = leftArr match {
            //无剩余,返回结果
            case Nil        => return rightArr
            //还剩一个位置,于头部补充1
            case h :: Nil   => return helper(Nil, 1 :: rightArr)
            //保持后面的位置不变, 更新元素对应的尾部位置
            case h1 :: h2 :: t => return helper(h2 :: t, h1 + h2 :: rightArr)
        }    
    }
    
  • 相关阅读:
    Split Temporary Variable
    Introduce Explaining Variable
    Replace Temp with Query
    Extract Method
    自测代码的价值
    代码的坏味道
    Divergent Change & Shotgun Surgery
    Large Class
    Long Method
    Duplicated Code
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/13472810.html
Copyright © 2011-2022 走看看