0
点赞
收藏
分享

微信扫一扫

算法探索_杨辉三角


问题描述:

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

算法探索_杨辉三角_Java

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

输入: 5
输出:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]


链接:​​​https://leetcode-cn.com/problems/pascals-triangle​​

解决思路:

  注释里我标注的很明白,这边不在赘述;

/*
*作者:赵星海
*时间:2020/8/27 11:24
*用途:杨辉三角
*/
public List<List<Integer>> generate(int numRows) {
//1.前两次执行不进入内循环
//2.第一次执行不添加尾部1
ArrayList<List<Integer>> listBig = new ArrayList<>();
//上一个集合
ArrayList<Integer> lastList = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
//---------子集合装填过程--------CSDN-深海呐----------
ArrayList<Integer> list = new ArrayList<>();
//头部1
list.add(1);
//中间数
for (int j = 1; j < i; j++) {
list.add(lastList.get(j - 1) + lastList.get(j));
}
//尾部1
if (i != 0) {
list.add(1);
}
//添加到大集合------------------------------
listBig.add(list);
//刷新上一个集合
lastList = list;
}
return listBig;
}

 

举报

相关推荐

0 条评论