zoukankan      html  css  js  c++  java
  • [LeetCode] Pascal's Triangle

    Question:

    Given numRows, generate the first numRows of Pascal's triangle.

    For example, given numRows = 5,
    Return

    [
         [1],
        [1,1],
       [1,2,1],
      [1,3,3,1],
     [1,4,6,4,1]
    ]

    1、题型分类:

    2、思路:先加上1,中间的根据上一层的结果计算,最后加上1

    3、时间复杂度:O(n^2)

    4、代码:

    public class Solution {
        public List<List<Integer>> generate(int numRows) {
            List<List<Integer>> list=new ArrayList<List<Integer>>();
            //special
            if(numRows<=0) return list;
            //general
            List<Integer> tempList=new ArrayList<Integer>();
            tempList.add(1);
            list.add(tempList);
            for(int i=1;i<numRows;i++)
            {
                tempList=new ArrayList<Integer>();
                List<Integer> ts=list.get(i-1);
                tempList.add(1);   //0
                for(int j=1;j<ts.size();j++)
                {
                    tempList.add(ts.get(j-1).intValue()+ts.get(j).intValue());
                }
                tempList.add(1);   //ts.size()
                list.add(tempList);
            }
            return list;
        }
    }

    5、优化:

    6、扩展:

  • 相关阅读:
    P1662 数7
    P3645 [APIO2015]雅加达的摩天楼
    P3396 哈希冲突
    P7479 至曾是英雄的您
    P7480 Reboot from Blue
    Apache Commons Collections
    ESP8266 WIFI杀手
    ESP8266 固件升级
    ESP8266 MicroPython安装与使用
    Window 安装子系统
  • 原文地址:https://www.cnblogs.com/maydow/p/4644921.html
Copyright © 2011-2022 走看看