【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;
    }
};
相关推荐
blasit5 小时前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_1 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星1 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛3 天前
delete又未完全delete
c++
端平入洛4 天前
auto有时不auto
c++
琢磨先生David5 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
哇哈哈20215 天前
信号量和信号
linux·c++
多恩Stone5 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马5 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝5 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode