《中英双解》leetCode Pascal‘s Triangle(杨辉三角)

Given an integer numRows, return the first numRows of Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

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

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

Example 1:

Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Example 2:

Input: numRows = 1
Output: [[1]]

 

杨辉三角大家都应该很熟悉,看到这一题大家可能都会有思路,我最初的想法是这样的,最上面一层,我们称为第1层,以此类推,,大家都发现了,第1层的树恒为1,这个时候为了提高效率可以单独拎出来进行判断,第二层也是一样。接下来就是难点,每个数都是他上面左上方和右上方数的和。这个时候我们应该怎么表示呢?

此时层数已经到了第三层,我们发现最左边和最右边的数还是1,此时我们就可以在每次循环的开头和结尾,创建一个List,并且执行add(1)方法。

下面就是核心部分,如何解决每个数是左上方和右上方数的和呢?我们目标层数还有可能不只是一个数,此时还需要考虑再一次的遍历,所以这个时候我们想到了暴力,两个for循环进行遍历。下面来看看代码。

class Solution {
    public List<List<Integer>> generate(int numRows) {
      List<List<Integer>> res = new ArrayList<>();
        if (numRows == 0) return res;
        res.add(new ArrayList<>(){{add(1);}});
        if (numRows == 1) return res;
        res.add(new ArrayList<>(){
            {
                add(1);
                add(1);
            }
        });
        if (numRows == 2) return res;
        
        List<Integer> preRow = res.get(1);
        for (int i = 3; i <= numRows; i++) {
            //首加一
            List<Integer> list = new ArrayList<>(){{add(1);}};
            for (int j = 1; j < i - 1; j++) {
                list.add(preRow.get(j) + preRow.get(j - 1));
            }
            //尾加一。放置数组下标越界异常
            list.add(1);
            preRow = list;
            res.add(list);
        }
        return res;
   }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值