Skip to content

Latest commit

 

History

History
47 lines (39 loc) · 1.06 KB

118. Pascal's Triangle.md

File metadata and controls

47 lines (39 loc) · 1.06 KB

118 Pascal's triangle

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] ]

Expalanation

  • two arraylis and care edge case first

Solution 1

class Solution {
    public List<List<Integer>> generate(int numRows) {
        if(numRows==0) return new ArrayList<List<Integer>>();
        ArrayList<List<Integer>> res = new ArrayList<List<Integer>>();
        ArrayList<Integer> temp = new ArrayList<>();
        temp.add(1);
        res.add(temp);
        for(int i = 1; i<numRows; i++){
            
            //cur row qual to preevious row
            ArrayList<Integer> l = new ArrayList<>();
            l.add(1);
            for(int j = 1; j<=i-1; j++){
                int prev = i-1;
                l.add(res.get(prev).get(j)+res.get(prev).get(j-1));
            }
            l.add(1);
            res.add(l);
        }
        return res;
    }
}