【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];
    }
}
相关推荐
hn小菜鸡4 小时前
LeetCode 377.组合总和IV
数据结构·算法·leetcode
Deepoch5 小时前
Deepoc 大模型:无人机行业的智能变革引擎
人工智能·科技·算法·ai·动态规划·无人机
heimeiyingwang9 天前
【深度学习加速探秘】Winograd 卷积算法:让计算效率 “飞” 起来
人工智能·深度学习·算法
时空自由民.9 天前
C++ 不同线程之间传值
开发语言·c++·算法
ai小鬼头9 天前
AIStarter开发者熊哥分享|低成本部署AI项目的实战经验
后端·算法·架构
小白菜3336669 天前
DAY 37 早停策略和模型权重的保存
人工智能·深度学习·算法
zeroporn9 天前
以玄幻小说方式打开深度学习词嵌入算法!! 使用Skip-gram来完成 Word2Vec 词嵌入(Embedding)
人工智能·深度学习·算法·自然语言处理·embedding·word2vec·skip-gram
亮亮爱刷题9 天前
飞往大厂梦之算法提升-7
数据结构·算法·leetcode·动态规划
_周游9 天前
【数据结构】_二叉树OJ第二弹(返回数组的遍历专题)
数据结构·算法
双叶8369 天前
(C语言)Map数组的实现(数据结构)(链表)(指针)
c语言·数据结构·c++·算法·链表·哈希算法