T118、杨辉三角

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

首先注意边界值处理(被坑了一万次),然后使用List中嵌套List时,对内部List做修改是,之前add的值也会发生修改,所以每次需要新new一个List出来(可能有更好的方式,等以后发掘)。还是对java了解不够深入,一直卡在这里,还是得多注重基础知识。

public static List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList<>();
        if(numRows==0)
            return res;
        List<Integer> temp = new ArrayList<>();
        temp.add(1);
        res.add(temp);
        if(numRows==1)
            return res;
        print(res);
        List<Integer> temp2 = new ArrayList<>();
        temp2.add(1);
        temp2.add(1);
        res.add(temp2);
        if(2==numRows)
            return res;
        for(int i = 2;i<=numRows;i++) {
            temp = new ArrayList<>();
            for(int j = 0;j<=i;j++) {
                if(0==j||j==i)
                    temp.add(1);
                else {
                    int t = res.get(i-1).get(j-1) + res.get(i-1).get(j);
                    temp.add(t);
                }
            }
            res.add(temp);  
        }
        return res;
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容