LeetCode每日一题: 杨辉三角(No.118)

栏目: 编程工具 · 发布时间: 6年前

给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
复制代码

示例:

LeetCode每日一题: 杨辉三角(No.118)
在杨辉三角中,每个数是它左上方和右上方的数的和。
复制代码

思考:

第一行为1,第二行开始,除了第一个和最后一个为1,其他的第i个等于迁移行的第i-1个加上前一行的第i个。
复制代码

实现:

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList<>();
        //0行直接返回
        if (numRows == 0) {
            return res;
        }
        //加入第一行的1
        res.add(new ArrayList<Integer>());
        res.get(0).add(1);
        //从第二行开始
        for (int count = 1; count < numRows; count++) {
            List<Integer> list = new ArrayList<>();
            res.add(list);
            for (int inner = 0; inner <= count; inner++) {
                //第一个和最后一个为1
                if (inner == 0 || inner == count) {
                    list.add(1);
                } else {//其他的等于前一行的第(inner - 1)个元素与第inner个元素相加
                    list.add(res.get(count - 1).get(inner - 1) + res.get(count - 1).get(inner));
                }
            }
        }
        return res;
    }
}复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Build Your Own Web Site the Right Way Using HTML & CSS

Build Your Own Web Site the Right Way Using HTML & CSS

Ian Lloyd / SitePoint / 2006-05-02 / USD 29.95

Build Your Own Website The Right Way Using HTML & CSS teaches web development from scratch, without assuming any previous knowledge of HTML, CSS or web development techniques. This book introduces you......一起来看看 《Build Your Own Web Site the Right Way Using HTML & CSS》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器