Leetcode 119. 杨辉三角 II

主要思路:先将杨辉三角的二维数组预处理出来,再根据题目要求,求出rowIndex行。

Python:

python 复制代码
class Solution:
    def getRow(self, rowIndex: int) -> List[int]:
        yh_trigle = [[0] * 34 for _ in range(34)]
        for i in range(34):
            yh_trigle[i][i] = 1
            yh_trigle[i][0] = 1
            for j in range(1, i):
                yh_trigle[i][j] = yh_trigle[i - 1][j] + yh_trigle[i - 1][j - 1]
        return yh_trigle[rowIndex][0: rowIndex + 1]

C++:(自己写的老出现越界的情况,实在不明白!!!,以下参考了灵神的代码,但是我的思路是一样的)

cpp 复制代码
const int MX = 34;
vector<int> c[MX];

auto init = []() {
    for (int i = 0; i < MX; i++) {
        c[i].resize(i + 1, 1);
        for (int j = 1; j < i; j++) {
            // 左上方的数 + 正上方的数
            c[i][j] = c[i - 1][j - 1] + c[i - 1][j];
        }
    }
    return 0;
}();

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        return c[rowIndex];
    }
};

加油!!!

相关推荐
用户2519162427111 小时前
Python之语言特点
python
刘立军2 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
沐怡旸3 小时前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥3 小时前
C++ 内存管理
c++
聚客AI3 小时前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
数据智能老司机5 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
大怪v6 小时前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
数据智能老司机6 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i8 小时前
django中的FBV 和 CBV
python·django
c8i8 小时前
python中的闭包和装饰器
python