【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];
    }
}
相关推荐
wearegogog1232 小时前
基于 MATLAB 的卡尔曼滤波器实现,用于消除噪声并估算信号
前端·算法·matlab
一只小小汤圆2 小时前
几何算法库
算法
Evand J2 小时前
【2026课题推荐】DOA定位——MUSIC算法进行多传感器协同目标定位。附MATLAB例程运行结果
开发语言·算法·matlab
leo__5203 小时前
基于MATLAB的交互式多模型跟踪算法(IMM)实现
人工智能·算法·matlab
忆锦紫3 小时前
图像增强算法:Gamma映射算法及MATLAB实现
开发语言·算法·matlab
t198751283 小时前
基于自适应Chirplet变换的雷达回波微多普勒特征提取
算法
guygg883 小时前
采用PSO算法优化PID参数,通过调用Simulink和PSO使得ITAE标准最小化
算法
老鼠只爱大米3 小时前
LeetCode算法题详解 239:滑动窗口最大值
算法·leetcode·双端队列·滑动窗口·滑动窗口最大值·单调队列
短剑重铸之日3 小时前
《7天学会Redis》Day2 - 深入Redis数据结构与底层实现
数据结构·数据库·redis·后端
mit6.8244 小时前
序列化|质数筛|tips|回文dp
算法