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];
    }
};

加油!!!

相关推荐
Hgfdsaqwr4 小时前
Django全栈开发入门:构建一个博客系统
jvm·数据库·python
TracyCoder1235 小时前
LeetCode Hot100(15/100)——54. 螺旋矩阵
算法·leetcode·矩阵
开发者小天5 小时前
python中For Loop的用法
java·服务器·python
老百姓懂点AI5 小时前
[RAG实战] 向量数据库选型与优化:智能体来了(西南总部)AI agent指挥官的长短期记忆架构设计
python
u0109272716 小时前
C++中的策略模式变体
开发语言·c++·算法
2501_941837266 小时前
停车场车辆检测与识别系统-YOLOv26算法改进与应用分析
算法·yolo
Aevget7 小时前
MFC扩展库BCGControlBar Pro v37.2新版亮点:控件功能进一步升级
c++·mfc·界面控件
六义义7 小时前
java基础十二
java·数据结构·算法
四维碎片7 小时前
QSettings + INI 笔记
笔记·qt·算法
Tansmjs7 小时前
C++与GPU计算(CUDA)
开发语言·c++·算法