Pascal's Triangle

题目
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

答案

class Solution {
    public List> generate(int numRows) {
        List> ans = new ArrayList<>();
        if(numRows == 0) return ans;
        
        List row = new ArrayList<>();
        row.add(1);
        ans.add(row);
        if(numRows == 1) return ans;
        
        for(int i = 2; i <= numRows; i++) {
            List new_row = new ArrayList<>();
            for(int j = 0; j <= row.size(); j++) {
                int left = (j - 1 >= 0) ? row.get(j - 1) : 0;
                int curr = (j < row.size()) ? row.get(j) : 0;
                
                new_row.add(left + curr);
            }
            ans.add(new_row);
            row = new_row;
        }
        return ans;
    }
}

你可能感兴趣的:(Pascal's Triangle)