118. Pascal's Triangle

mac2026-03-29  9

Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle. In Pascal’s triangle, each number is the sum of the two numbers directly above it.

class Solution { public List<List<Integer>> generate(int numRows) { List<List<Integer>> result = new ArrayList<>(); for (int i = 1; i <= numRows; i++) { List<Integer> level = new ArrayList<>(); for (int j = 0; j < i; j++) { if (j == 0 || j == i - 1) { level.add(1); } else { level.add(result.get(i - 2).get(j - 1) + result.get(i - 2).get(j)); } } result.add(level); } return result; } }
最新回复(0)