【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];
    }
}
相关推荐
BanyeBirth5 分钟前
C++窗口问题
开发语言·c++·算法
前端小L2 小时前
图论专题(十五):BFS的“状态升维”——带着“破壁锤”闯迷宫
数据结构·算法·深度优先·图论·宽度优先
2501_941805933 小时前
人工智能与大数据:驱动新时代的创新与决策
leetcode
橘颂TA4 小时前
【剑斩OFFER】算法的暴力美学——连续数组
c++·算法·leetcode·结构与算法
星释5 小时前
Rust 练习册 72:多米诺骨牌与回溯算法
开发语言·算法·rust
福尔摩斯张7 小时前
Axios源码深度解析:前端请求库设计精髓
c语言·开发语言·前端·数据结构·游戏·排序算法
算法与编程之美8 小时前
提升minist的准确率并探索分类指标Precision,Recall,F1-Score和Accuracy
人工智能·算法·机器学习·分类·数据挖掘
MicroTech20258 小时前
微算法科技(NASDAQ :MLGO)混合共识算法与机器学习技术:重塑区块链安全新范式
科技·算法·区块链
李牧九丶8 小时前
从零学算法1334
前端·算法
在繁华处8 小时前
C语言经典算法:汉诺塔问题
c语言·算法