当前位置: 首页 > news >正文

【Leetcode 每日一题】119. 杨辉三角 II

问题背景

给定一个非负索引 r o w I n d e x rowIndex rowIndex,返回「杨辉三角」的第 r o w I n d e x rowIndex rowIndex 行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。

数据约束

  • 0 ≤ r o w I n d e x ≤ 33 0 \le rowIndex \le 33 0rowIndex33

解题过程

这题其实之前做过,定义列表并且按规则计算对应位置上的值即可。
另外考虑到要求的结果范围有限,也可以先打表,根据实际情况返回结果。这种做法严格地说来不符合 O ( r o w I n d e x ) O(rowIndex) O(rowIndex) 的空间要求,但其实效率非常不错。

具体实现

模拟计算

class Solution {public List<Integer> getRow(int rowIndex) {if (rowIndex == 0) {return List.of(1);}List<Integer> pre = new ArrayList<>();pre.add(1);pre.add(1);List<Integer> res;while (--rowIndex > 0) {res  = new ArrayList<>(pre);for (int i = 1; i < pre.size(); i++) {res.set(i, pre.get(i - 1) + pre.get(i));}res.add(1);pre = new ArrayList<>(res);}return pre;}
}

打表预处理

class Solution {private static final int MAX_N = 34;private static final List<Integer>[] res = new List[MAX_N];static {res[0] = List.of(1);for (int i = 1; i < res.length; i++) {List<Integer> row = new ArrayList<>(i + 1);row.add(1);for (int j = 1; j < i; j++) {row.add(res[i - 1].get(j - 1) + res[i - 1].get(j));}row.add(1);res[i] = row;}}public List<Integer> getRow(int rowIndex) {return res[rowIndex];}
}
http://www.lryc.cn/news/530284.html

相关文章:

  • 简单看看会议系统2(时延分析)(TODO)
  • Linux中 端口被占用如何解决
  • OpenAI o3-mini全面解析:最新免费推理模型重磅发布
  • C++:虚函数与多态性习题2
  • 利用metaGPT多智能体框架实现智能体-1
  • Kubernetes组成及常用命令
  • oracle: 多表查询之联合查询[交集intersect, 并集union,差集minus]
  • 力扣第149场双周赛
  • AI开发之 ——Anaconda 介绍
  • Spring中ObjectProvider的妙用与实例解析
  • Easy系列PLC尺寸测量功能块(激光微距应用)
  • 当卷积神经网络遇上AI编译器:TVM自动调优深度解析
  • 《网络编程基础之完成端口模型》
  • Axure PR 9 旋转效果 设计交互
  • 完美还是完成?把握好度,辨证看待
  • C++的类Class
  • C++中的内存管理
  • MySQL为什么默认引擎是InnoDB ?
  • ComfyUI安装调用DeepSeek——DeepSeek多模态之图形模型安装问题解决(ComfyUI-Janus-Pro)
  • 电脑要使用cuda需要进行什么配置
  • 利用Muduo库实现简单且健壮的Echo服务器
  • Scratch 《像素战场》系列综合游戏:像素战场游戏Ⅰ~Ⅲ 介绍
  • Android学习制作app(ESP8266-01S连接-简单制作)
  • 三甲医院大型生信服务器多配置方案剖析与应用(2024版)
  • 【Unity3D】实现横版2D游戏——单向平台(简易版)
  • 大白话讲清楚embedding原理
  • 电脑优化大师-解决电脑卡顿问题
  • el-table组件样式如何二次修改?
  • java练习(1)
  • UbuntuWindows双系统安装