栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

2021.10.01 - 105.杨辉三角

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

2021.10.01 - 105.杨辉三角

文章目录
  • 1. 题目
  • 2. 思路
    • (1) 递归
    • (2) 模拟法
  • 3. 代码

1. 题目

2. 思路 (1) 递归
  • 利用递归得到上一层的结果,根据上一层的结果计算这一层的结果即可。
(2) 模拟法
  • 根据规则从上往下推出每一层的结果即可。
3. 代码
import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
    }
}

class Solution {
    public List> generate(int numRows) {
        if (numRows == 1) {
            return new ArrayList>() {{
                add(new ArrayList() {{
                    add(1);
                }});
            }};
        }
        List> res = generate(numRows - 1);
        List pre = res.get(res.size() - 1);
        List cur = new ArrayList<>();
        cur.add(1);
        for (int i = 1; i < pre.size(); i++) {
            cur.add(pre.get(i - 1) + pre.get(i));
        }
        cur.add(1);
        res.add(cur);
        return res;
    }
}

class Solution1 {
    public List> generate(int numRows) {
        List> res = new ArrayList<>();
        List cur = new ArrayList<>();
        cur.add(1);
        res.add(cur);
        List pre = cur;
        while (numRows > 1) {
            cur = new ArrayList<>();
            cur.add(1);
            for (int i = 1; i < pre.size(); i++) {
                cur.add(pre.get(i - 1) + pre.get(i));
            }
            cur.add(1);
            res.add(cur);
            pre = cur;
            numRows--;
        }
        return res;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/284430.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号