0118. Pascal's Triangle

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

Description

Given an integer numRows, return the first numRows of Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

**Input:** numRows = 5
**Output:** [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Example 2:

**Input:** numRows = 1
**Output:** [[1]]

Constraints:

  • 1 <= numRows <= 30

ac

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();

        // edge cases
        if (numRows <= 0) return res;

        // iteration
        for (int i = 0; i < numRows; i++) {
            List<Integer> curr = new ArrayList<Integer>();
            curr.add(1);

            if (i != 0) {
                List<Integer> prev = res.get(res.size() - 1);
                for (int j = 0; i > 1 && j < prev.size() - 1; j++) {
                    int tmp = prev.get(j) + prev.get(j+1);
                    curr.add(tmp);
                }
                curr.add(1);
            }

            res.add(curr);
        }

        return res;
    }
}
/*
iteration


recursion
*/

Last updated