【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];
    }
}
相关推荐
夏鹏今天学习了吗31 分钟前
【LeetCode热题100(95/100)】寻找重复数
算法·leetcode·职场和发展
TTGGGFF4 小时前
控制系统建模仿真(四):线性控制系统的数学模型
人工智能·算法
晚风吹长发4 小时前
初步了解Linux中的命名管道及简单应用和简单日志
linux·运维·服务器·开发语言·数据结构·c++·算法
圣保罗的大教堂4 小时前
leetcode 3315. 构造最小位运算数组 II 中等
leetcode
Σίσυφος19005 小时前
Halcon中霍夫直线案例
算法
夏乌_Wx5 小时前
练题100天——DAY42:移除链表元素 ★★☆☆☆
数据结构
Anastasiozzzz5 小时前
leetcode力扣hot100困难题--4.俩个正序数列的中位数
java·算法·leetcode·面试·职场和发展
BHXDML5 小时前
第六章:推荐算法
算法·机器学习·推荐算法
Tisfy6 小时前
LeetCode 3510.移除最小数对使数组有序 II:有序集合
算法·leetcode·题解·设计·有序集合
汉克老师6 小时前
GESP2025年9月认证C++五级真题与解析(单选题9-15)
c++·算法·贪心算法·排序算法·归并排序·gesp5级·gesp五级