博客
关于我
LeetCode119.杨辉三角2Golang版
阅读量:382 次
发布时间:2019-03-05

本文共 677 字,大约阅读时间需要 2 分钟。

要解决给定一个非负索引 k,返回杨辉三角的第 k 行的问题,我们可以利用杨辉三角的性质,即每一行的数是其左右邻居的和。通过动态计算组合数,我们可以直接生成每一行的数值。

方法思路

杨辉三角的每一行可以看作是组合数的序列。第 k 行的数是组合数 C(k, 0), C(k, 1), ..., C(k, k)。为了生成第 k 行,我们可以从左到右依次计算每个位置的值。具体来说,第 i 个数可以通过前一个数乘以 (k - i + 1) 再除以 i 来计算。

解决代码

func getRow(rowIndex int) []int {    yanghui := make([]int, rowIndex + 1)    yanghui[0] = 1    for i := 1; i <= rowIndex; i++ {        yanghui[i] = yanghui[i-1] * (rowIndex - i + 1) / i    }    return yanghui}

代码解释

  • 初始化数组:创建一个长度为 rowIndex + 1 的数组 yanghui,并将第一个元素初始化为 1。
  • 计算每个位置的值:从 i=1 到 i=rowIndex,依次计算每个位置的值。使用公式 yanghui[i] = yanghui[i-1] * (rowIndex - i + 1) / i 来计算每个位置的值。
  • 返回结果:返回生成的杨辉三角第 k 行的数组。
  • 这种方法通过直接计算组合数,避免了传统杨辉三角生成方式中的复杂循环和覆盖问题,实现简洁高效。

    转载地址:http://nlcwz.baihongyu.com/

    你可能感兴趣的文章
    No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    no1
    查看>>
    NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
    查看>>