LeetCode——118. Pascal's Triangle

题目原址

https://leetcode.com/problems/pascals-triangle/description/

题目描述

Given numRows, generate the first numRows of Pascal’s triangle.
For example, given numRows = 5,
Return
这里写图片描述

解题思路

帕斯卡三角(杨辉三角),这道题的AC代码有几点需要注意的地方,通过这道题特别适合学习ArrayList类。

  • 首先题目要求返回类型为:List<List<Integer>>,因此想到的就是定义一个返回类型为List<List<Integer>>的变量list,但是List里面存储的值的类型是List<Interger>所以,又定义了一个List<Interger>类型的变量arrayList
  • 其次,变量定义完了,怎么实现杨辉三角的各个位置的值呢?首先想到的肯定是当前层i用到i-1层对应的两个元素,博主当初也是这么想的,但是如果是这样的话,就要使用数组,然后判断边界,如果第i层就是第一层,那怎么办?因此需要判断的临界条件太多。SO。换思路!直接使用ArrayList变量,在for循环中,每次都向arrayList中增加一个元素,注意下面的AC代码写的是arrayList.add(0, 1);,所以要理解好add(0,1)它是怎么将元素加进集合中的,我特意查了API。官方!文档!告诉我说。Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices). 意思就是如果想要插入元素,就将当前的元素向右移动,然后把当前插入的元素插入到指定的位置,即如果集合中有{1,2,3,4},现在想要调用arrayList.add(0, 1);那么执行的结果是{1,1,2,3,4},所以,每次进循环arrayList中就会增加一个元素,实际上arrayList集合每次循环都添加一个元素,没添加一个元素,更改值后都将它放在list中,第二次循环时,arrayList沿用上次循环的结果。
  • 然后再进入第二层循环,在第二层循环中,做的操作就很容易理解了,这一步很神奇哦,不是按照当前层是上一层的两个元素和,而是按照当前的元素值 = 当前元素值 + 当前元素的后一个元素值实现的。最后注意这个内层循环中,循环终止条件是arrayList.size() - 1,这样就避免判断临界条件了!
  • 最后,最后一步也是一个陷阱,注意,一定要是list.add(new ArrayList(arrayList));,每一次都新new一个对象将arrayList的值存进去,一定不能使list.add(arrayList);至于原因。自己想!!!

AC代码

class Solution {
    public List<List<Integer>> generate(int numRows) {

        List<List<Integer>> list = new ArrayList<List<Integer>>();
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        for(int i = 0; i < numRows; i++) {
                arrayList.add(0, 1);
                for(int j = 1; j < arrayList.size() - 1; j++) {
                    arrayList.set(j, arrayList.get(j) + arrayList.get(j + 1));
                }
                list.add(new ArrayList(arrayList));
        }
        return list;
    }
}

感谢

https://discuss.leetcode.com/topic/6805/my-concise-solution-in-java

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值