领扣LintCode算法问题答案-1355. 杨辉三角

    科技2022-07-13  133

    领扣LintCode算法问题答案-1355. 杨辉三角

    目录

    1355. 杨辉三角描述样例 1:样例 2: 题解鸣谢

    1355. 杨辉三角

    描述

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

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

    样例 1:

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

    样例 2:

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

    题解

    public class Solution { /** * @param numRows: num of rows * @return: generate Pascal's triangle */ public List<List<Integer>> generate(int numRows) { // write your code here List<List<Integer>> ret = new ArrayList<>(); List<Integer> lastRow = new ArrayList<>(); lastRow.add(1); ret.add(lastRow); for (int i = 1; i < numRows; i++) { List<Integer> row = new ArrayList<>(); row.add(1); lastRow = ret.get(i - 1); for (int j = 1; j < i; j++) { row.add(lastRow.get(j) + lastRow.get(j - 1)); } row.add(1); ret.add(row); } return ret; } }

    原题链接点这里

    鸣谢

    非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。 欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。

    Processed: 0.011, SQL: 8