LeetCode——119. 杨辉三角 II

题目

给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 行。

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

示例:

输入: 3
输出: [1,3,3,1]

解题思路 

用之前的杨辉三角1里的方法生成34层杨辉三角,然后直接从lists里get就好.

代码实现

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;
    }
    
    public List<Integer> getRow(int rowIndex) {
        // 先返回33层的杨辉三角
        List<List<Integer>> lists = generate(34);
        // 第k行
        return lists.get(rowIndex);
    }
}

 

猜你喜欢

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