zoukankan      html  css  js  c++  java
  • 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]
    ]

    //Time: (m * n), Space: O(m * n)  
      public List<List<Integer>> generate(int numRows) {
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            
            if (numRows <= 0) {
                return result;
            }
            
            List<Integer> first = new ArrayList<Integer>();
            first.add(1);
            result.add(first);//先把第一层特殊的放入result
            
            for (int i = 1; i < numRows; i++) {//注意i从1开始i因为在外面已经有了第0层
                List<Integer> temp = new ArrayList<Integer>();
                temp.add(1);//每层第一个
                
                for (int j = 1; j < i; j++) {////注意j从1开始i因为在外面已经有了第0列
                    temp.add(result.get(i - 1).get(j) + result.get(i - 1).get(j - 1));
                }
                
                temp.add(1);//每层最后一个
                result.add(temp);
            }
            
            return result;
        }
  • 相关阅读:
    005 HTML+CSS(Class027
    004 HTML+CSS(Class024
    003 HTML+CSS(Class011
    002HTML+CSS(class007-010)
    001HTML+CSS(class001-006)
    021 vue路由vue-router
    020 Vue 脚手架CLI的使用
    019 Vue webpack的使用
    018 vue的watch属性
    017 vue的插槽的使用
  • 原文地址:https://www.cnblogs.com/jessie2009/p/9778655.html
Copyright © 2011-2022 走看看