首页 > 编程语言 > 详细

杨辉三角(java)

时间:2021-02-01 17:13:18      阅读:22      评论:0      收藏:0      [点我收藏+]

题目描述:给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。

(题目链接:https://leetcode-cn.com/problems/pascals-triangle/)

解题代码:

 1     public List<List<Integer>> generate(int numRows) {
 2         // 若输入的行数小于等于0,则返回空列表,表示没有数据。
 3         if(numRows <= 0)
 4             return new ArrayList<>();
 5         List<List<Integer>> result = new ArrayList<>(); // 保存整个数据
 6         // 创建第一行列表并添加到result中
 7         List<Integer> firstLine = new ArrayList<>();
 8         firstLine.add(1);
 9         result.add(firstLine);
10         if(numRows == 1)
11             return result;
12         // 创建第二行列表并添加到result中
13         List<Integer> secondLine = new ArrayList<>();
14         secondLine.add(1);
15         secondLine.add(1);
16         result.add(secondLine);// 将第二行的列表加载到result中
17         if(numRows == 2)
18             return result;
19         // 依次添加后面每行列表
20         for(int i = 3; i <= numRows; i++){
21             List<Integer> frontLine = result.get(i-1-1);
22             List<Integer> tmp = new ArrayList<>(); // 第三行开始的每一行
23             tmp.add(1);
24             for(int j = 1; j < i-1; j++){
25                 int left = frontLine.get(j-1);
26                 int right = frontLine.get(j);
27                 tmp.add(left+right);
28             }
29             tmp.add(1);
30             result.add(tmp);
31         }
32         return result;
33     }

 

杨辉三角(java)

原文:https://www.cnblogs.com/lyf98/p/14357146.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!