LeetCode:118.杨辉三角

mac2025-06-22  8

题目:

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

示例:

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

源码:

class Solution { public List<List<Integer>> generate(int numRows) { if (numRows <= 0) { return new ArrayList<>(); } List<List<Integer>> result = new ArrayList<>(); List<Integer> FirstLine = new ArrayList<>(); FirstLine.add(1); result.add(FirstLine); if (numRows == 1) { return result; } List<Integer> SecondLine = new ArrayList<>(); SecondLine.add(1); SecondLine.add(1); result.add(SecondLine); if (numRows == 2) { return result; } for (int row = 3; row <= numRows; row++) { List<Integer> prevLine = result.get(row - 1 - 1); List<Integer> curLine = new ArrayList<>(); curLine.add(1); for (int col = 1; col < row - 1; col++) { curLine.add(prevLine.get(col - 1) + prevLine.get(col)); } curLine.add(1); result.add(curLine); } return result; } }
最新回复(0)