L118. Pascal's Triangle

DP

Problem:

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.

Example:

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

Solution:

public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList<>();
        
        for(int i = 0; i < numRows; i++){
            List<Integer> list = new ArrayList<>();
            for(int j = 0; j < i + 1; j++){
                if(j == 0 || j == i){
                    list.add(1);
                }else{
                    int a = res.get(i - 1).get(j - 1);
                    int b = res.get(i - 1).get(j);
                    list.add(a + b);
                }
                
            }
            res.add(list);
        }
        return res;
    }

Last updated

Was this helpful?