【LeetCode】118. 杨辉三角

题目链接


文章目录

Python3

直觉解法:

python 复制代码
class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        ans = [[1]]
        for _ in range(numRows-1):
            temp1 = []
            temp2 = [0] + ans[-1] + [0]
            for i in range(len(temp2)-1) :
                temp1.append(temp2[i]+temp2[i+1])
            ans.append(temp1)

        return ans 

版本1

以下的理论介绍 可以说和 本题的 代码实现 毫无关系。

这个版本 需要注意 列表的边界

python 复制代码
class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        ans = []
        for i in range(numRows):
            row = []  # 第 i 行
            for j in range(i+1) : # 第 i 行 【0开始】 有 i+1 项
                if j == 0 or j == i: # 为 1 的位置下标 和 行下标 一致 
                    row.append(1) 
                else:
                    row.append(ans[i-1][j]+ans[i-1][j-1])
            ans.append(row)

        return ans 

⭐ 版本2

思路: 前一行 两端 补0 模拟。 结合 动图 理解

python 复制代码
class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        ans = [[1]]
        for _ in range(numRows-1):  # 因为 直接对前一行ans[-1]操作,这里要注意循环次数 第0次循环  获得了 第2行。因此只到 第 numRows-2 次循环
            row = []  # 存储 每行的数 
            temp = [0] + ans[-1] + [0]
            for i in range(len(temp)-1) :
                row.append(temp[i] + temp[i+1])
            ans.append(row)

        return ans 

C++

⭐ 版本

题目 说明至少 一行,可以跳过 第一行的处理

cpp 复制代码
class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> ans;  // 这里没有限制长度
        ans.push_back(vector<int>(1, 1));   //  第 1 行
        for (int i = 1; i <= numRows-1; ++i){
            ans.push_back(vector<int>(i+1));  // C++ 不能随便 加元素,要提前说明
            ans[i][0] = ans[i][i] = 1;
            for(int j = 1; j <= i-1; ++j){
                ans[i][j] = ans[i-1][j] + ans[i-1][j-1];
            }
        }
        return ans;
    }
};

官方版本

cpp 复制代码
class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> ans(numRows);
        for (int i = 0; i <= numRows-1; ++i){
            ans[i].resize(i+1);  // C++ 不能随便 加长,要提前说明
            ans[i][0] = ans[i][i] = 1;
            for(int j = 1; j <= i-1; ++j){
                ans[i][j] = ans[i-1][j] + ans[i-1][j-1];
            }
        }
        return ans;
    }
};
相关推荐
AA陈超4 小时前
虚幻引擎5 GAS开发俯视角RPG游戏 P06-14 属性菜单 - 文本值行
c++·游戏·ue5·游戏引擎·虚幻
云知谷4 小时前
【经典书籍】C++ Primer 第15章类虚函数与多态 “友元、异常和其他高级特性” 精华讲解
c语言·开发语言·c++·软件工程·团队开发
weixin_582985185 小时前
OpenCV cv::Mat.type() 以及类型数据转换
c++·opencv·计算机视觉
爱coding的橙子7 小时前
每日算法刷题Day78:10.23:leetcode 一般树7道题,用时1h30min
算法·leetcode·深度优先
Swift社区7 小时前
LeetCode 403 - 青蛙过河
算法·leetcode·职场和发展
oioihoii8 小时前
深入理解 C++ 现代类型推导:从 auto 到 decltype 与完美转发
java·开发语言·c++
报错小能手8 小时前
项目——基于C/S架构的预约系统平台 (1)
开发语言·c++·笔记·学习·架构
lingran__8 小时前
算法沉淀第十天(牛客2025秋季算法编程训练联赛2-基础组 和 奇怪的电梯)
c++·算法
Dream it possible!9 小时前
LeetCode 面试经典 150_链表_两数相加 (57_2_C++_中等)
leetcode·链表·面试
oioihoii10 小时前
当无符号与有符号整数相遇:C++中的隐式类型转换陷阱
java·开发语言·c++