【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 0≤rowIndex≤33

解题过程

这题其实之前做过,定义列表并且按规则计算对应位置上的值即可。

另外考虑到要求的结果范围有限,也可以先打表,根据实际情况返回结果。这种做法严格地说来不符合 O ( r o w I n d e x ) O(rowIndex) O(rowIndex) 的空间要求,但其实效率非常不错。

具体实现

模拟计算

java 复制代码
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;
    }
}

打表预处理

java 复制代码
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];
    }
}
相关推荐
不能只会打代码几秒前
蓝桥杯--生命之树(Java)
java·算法·蓝桥杯·动态规划·贪心
MobotStone7 分钟前
三步高效拆解顶刊论文
算法
CreasyChan8 分钟前
unity射线与几何检测 - “与世界的交互”
算法·游戏·3d·unity·数学基础
leiming621 分钟前
C++ 类模板对象做函数参数
开发语言·c++·算法
王老师青少年编程21 分钟前
csp信奥赛C++标准模板库STL案例应用1
c++·算法·stl·标准模板库·csp·信奥赛·binary_search
NAGNIP28 分钟前
Kimi Linear——有望替代全注意力的全新注意力架构
算法·面试
耶叶34 分钟前
B树知识点总结
数据结构·b树
智驱力人工智能43 分钟前
无人机河道漂浮物检测 从项目构建到价值闭环的系统工程 无人机河道垃圾识别 农村河道漂浮物智能清理方案 无人机辅助河道清洁预警
opencv·算法·安全·yolo·目标检测·无人机·边缘计算
德福危险1 小时前
C语言数据类型与变量 系统总结笔记
c语言·笔记·算法
@淡 定1 小时前
JVM调优参数配置详解
java·jvm·算法