美文网首页
Pascal's Triangle

Pascal's Triangle

作者: BLUE_fdf9 | 来源:发表于2018-10-19 12:16 被阅读0次

    题目
    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;
        }
    }
    

    相关文章

      网友评论

          本文标题:Pascal's Triangle

          本文链接:https://www.haomeiwen.com/subject/myeyzftx.html