美文网首页
[LeetCode 118] Pascal's Triangle

[LeetCode 118] Pascal's Triangle

作者: 灰睛眼蓝 | 来源:发表于2019-07-19 12:17 被阅读0次

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

    image

    <small style="box-sizing: border-box; font-size: 11.2px;">In Pascal's triangle, each number is the sum of the two numbers directly above it.</small>

    Example:

    **Input:** 5
    **Output:**
    [
         [1],
        [1,1],
       [1,2,1],
      [1,3,3,1],
     [1,4,6,4,1]
    ]
    
    class Solution {
        public List<List<Integer>> generate(int numRows) {
            List<List<Integer>> result = new ArrayList<> ();
            if (numRows <= 0)
                return result;
            
            for (int row = 1; row <= numRows; row ++) {
                List<Integer> rowEntry = new ArrayList<> ();
                
                if (row == 1) {
                    rowEntry.add (1);
                    result.add (rowEntry);
                    continue;
                }
                
                List<Integer> lastRow = result.get (row - 2);
                
                for (int col = 0; col < row; col ++) {
                    if (col == 0 || col == row - 1) {
                        rowEntry.add (1);
                        continue;
                    }
                    
                    
                    int first = lastRow.get (col - 1);
                    int second = lastRow.get (col);
                    rowEntry.add (first + second);
                }
                
                result.add (rowEntry);
            }
            
            return result;
        }
    }
    

    相关文章

      网友评论

          本文标题:[LeetCode 118] Pascal's Triangle

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