LeetCode——118. 杨辉三角

题目

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

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

示例:

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

 解题思路

1、 层数为0,直接返回[];

2、 层数为1, 直接返回[1];

3、 层数为2, 直接返回[[1], [1,1]]

4、层数超过2,下一层的值由上一层求得。

代码实现 

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> reLists = new LinkedList();
        List<Integer> up = new LinkedList();     // 上一层
        
        List<Integer> list1 = new LinkedList();  // 第一层 [1]
        list1.add(1);            
        
        List<Integer> list2 = new LinkedList();  // 第二层 [1, 1]
        list2.add(1);
        list2.add(1);
        // 0层 直接返回空的
        if (numRows == 0) {
            return reLists;
        }
        // 一层 直接返回 第一层
        if (numRows == 1) {
            reLists.add(list1);
            return  reLists;
        }
        // 二层 直接返回[1,1]第一二层
         if (numRows == 2) {
            reLists.add(list1);
            reLists.add(list2);
            return  reLists;
        }
        
        // 超过 二层 先初始化
        reLists.add(list1);
        reLists.add(list2);
        // 开始上一层up 为 第二层
        up = list2;
        // 循环遍历 reLists 添加剩下的层
        for (int i = 0; i < numRows - 2; i++) {
            List<Integer> current = new LinkedList();  // 当前层
            current.add(1);
            current.add(1);
            // 遍历 up 层得到当前层,每次添加元素添加在倒数第二个位置
            for (int j = 0; j < up.size() - 1; j ++) {
                current.add(current.size() - 1, up.get(j) + up.get(j+1));
            }
            reLists.add(current);
            up = current;
        }
        
        return reLists;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41722272/article/details/82784749