首页 > 其他分享 >leetcode-118-easy

leetcode-118-easy

时间:2022-11-01 20:12:45浏览次数:64  
标签:pre int List 118 numRows Pascal easy new leetcode

Pascal's Triangle

Given an integer numRows, return the first numRows of Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:


Example 1:

Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Example 2:

Input: numRows = 1
Output: [[1]]
Constraints:

1 <= numRows <= 30

思路一:观察每行的规律,可以发现每一行的 0 和 length-1 固定为 1,其他的位置 i 的值固定为上一行的 i-1 值加上 i 值,完全分类有

  • 位置 0, length-1 -> 1
  • 位置 i -> pre[i-1] + pre[i]
public List<List<Integer>> generate(int numRows) {
    List<List<Integer>> list = new ArrayList<>();
    List<Integer> one = new ArrayList<>();
    one.add(1);
    list.add(one);

    List<Integer> pre = one;
    for (int i = 2; i <= numRows; i++) {

        List<Integer> temp = new ArrayList<>();
        for (int j = 1; j <= i; j++) {
            if (j == 1 || j == i) {
                temp.add(1);
            } else {
                temp.add(pre.get(j - 1 - 1) + pre.get(j - 1));
            }
        }
        pre = temp;
        list.add(temp);
    }

    return list;
}

标签:pre,int,List,118,numRows,Pascal,easy,new,leetcode
From: https://www.cnblogs.com/iyiluo/p/16848960.html

相关文章

  • leetcode-1137-easy
    N-thTribonacciNumberTheTribonaccisequenceTnisdefinedasfollows:T0=0,T1=1,T2=1,andTn+3=Tn+Tn+1+Tn+2forn>=0.Givenn,returnthe......
  • python: easyocr的安装和使用(easyocr 1.6.2 / Python 3.7.15 )
    一,安装easyocr:1,官网:https://www.jaided.ai/项目代码地址:https://github.com/JaidedAI/EasyOCR通过pip安装:[root@blog~]#pip3installeasyocr查看......
  • 如何在EasyCVR平台配置AI智能识别的微信端告警消息推送?
    我们在此前的文章中和大家分享过关于EasyCVR视频融合平台智能告警相关的开发及功能介绍,其中包括微信端的开发流程分享,感兴趣的用户可以翻阅往期的文章进行了解。智能告警功......
  • EasyCVR平台基于萤石云SDK接入的设备播放流程及接口调用
    EasyCVR视频融合云服务支持海量视频汇聚与管理、处理与分发、智能分析等视频能力,在功能上,可支持视频监控直播、云端录像、云存储、录像检索与回看、智能告警、平台级联、服......
  • EasyCVR视频融合平台添加萤石云SDK接入的设计与开发流程
    我们在前期的文章中介绍过关于EasyCVR近期新增了多个功能,包括SDK接入方式的拓展。经过一段时间的设计、开发与测试,EasyCVR平台已经支持稳定接入华为SDK、宇视SDK、乐橙SDK、......
  • leetcode111-二叉树的最小深度
    111.二叉树的最小深度 这道题相比 104.二叉树的最大深度 还是难上一些的,但也不算太难。BFS/***Definitionforabinarytreenode.*structTreeNode{......
  • leetcode-2. 两数相加
    题目描述给你两个 非空的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。请你将两个数相加,并以相同形式返回一......
  • LeetCode 236. 二叉树的最近公共祖先 - 回溯的理解
    题目https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/思路自己做只摸到一些门道,还是靠随想录...代码:deflowestCommonAncestor(self,root:'......
  • LeetCode_144_二叉树的前序遍历
    题目描述:给定一个二叉树,返回它的前序遍历。示例:输入:[1,null,2,3]1\2/3输出:[1,2,3]进阶:递归算法很简单,你可以通过迭代算法完成吗?递归的写法......
  • LeetCode_572_另一个树的子树
    题目描述:给定两个非空二叉树s和t,检验s中是否包含和t具有相同结构和节点值的子树。s的一个子树包括s的一个节点和这个节点的所有子孙。s也可以看做它自身的一棵子......