zoukankan      html  css  js  c++  java
  • leetcode -- Pascal's Triangle

    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]
    ]

    [解题思路]

    第三行开始,每行除边界元素外,每个元素ai都是由ai-1 + ai构成

     1 public class Solution {
     2     public ArrayList<ArrayList<Integer>> generate(int numRows) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
     6         if(numRows <= 0){
     7             return result;
     8         }
     9         // row 1
    10         ArrayList<Integer> one = new ArrayList<Integer>();
    11         one.add(1);
    12         result.add(one);
    13         if(numRows == 1){
    14             return result;
    15         }
    16         // row 2
    17         ArrayList<Integer> two = new ArrayList<Integer>();
    18         two.add(1);
    19         two.add(1);
    20         result.add(two);
    21         if(numRows == 2){
    22             return result;
    23         }
    24         for(int i = 3; i <= numRows; i++){
    25             int resultSize = result.size();
    26             ArrayList<Integer> last = result.get(resultSize - 1);
    27             ArrayList<Integer> cur = new ArrayList<Integer>();
    28             for(int j = 1; j <= i; j++){
    29                 if(j == 1 || j == i){
    30                     cur.add(1);
    31                 } else {
    32                     int num = last.get(j - 1) + last.get(j - 2);
    33                     cur.add(num);
    34                 }
    35             }
    36             result.add(cur);
    37         }
    38         return result;
    39     }
    40 }
  • 相关阅读:
    python-web微信实现
    Python---BeautifulSoup模块
    Python—requests模块详解
    KindEditor编辑器
    Django实现瀑布流,组合搜索
    利用(CMD)在Django中创建文件
    ppt插入声音
    高性能mysql 第1,2,3章。
    mysql复制
    最长DNA重复序列长度,并输出该序列。 JAVA
  • 原文地址:https://www.cnblogs.com/feiling/p/3277123.html
Copyright © 2011-2022 走看看