【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];
    }
}
相关推荐
py有趣36 分钟前
力扣热门100题之不同路径
算法·leetcode
_日拱一卒1 小时前
LeetCode:25K个一组翻转链表
算法·leetcode·链表
啊哦呃咦唔鱼1 小时前
LeetCodehot100-394 字符串解码
算法
小欣加油1 小时前
leetcode2078 两栋颜色不同且距离最远的房子
数据结构·c++·算法·leetcode·职场和发展
我真不是小鱼1 小时前
cpp刷题打卡记录30——轮转数组 & 螺旋矩阵 & 搜索二维矩阵II
数据结构·c++·算法·leetcode
逻辑驱动的ken3 小时前
Java高频面试考点场景题09
java·开发语言·数据库·算法·oracle·哈希算法·散列表
帅小伙―苏3 小时前
力扣42接雨水
前端·算法·leetcode
AI科技星3 小时前
精细结构常数α的几何本源:从第一性原理的求导证明、量纲分析与全域验证
算法·机器学习·数学建模·数据挖掘·量子计算
6Hzlia3 小时前
【Hot 100 刷题计划】 LeetCode 287. 寻找重复数 | C++ 数组判环 (快慢指针终极解法)
c++·算法·leetcode
MegaDataFlowers3 小时前
26.删除有序数组中的重复项
算法