Pascal's Triangle

2018-10-19  本文已影响0人  BLUE_fdf9

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

答案

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> ans = new ArrayList<>();
        if(numRows == 0) return ans;
        
        List<Integer> row = new ArrayList<>();
        row.add(1);
        ans.add(row);
        if(numRows == 1) return ans;
        
        for(int i = 2; i <= numRows; i++) {
            List<Integer> 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;
    }
}
上一篇下一篇

猜你喜欢

热点阅读