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列表(即数组)
    Python中的关键字和内置函数
    python的变量和数据类型
    将数据写入本地txt
    Notepad++配置Python开发环境
    java中方法复写的作用进一步理解
    this表示当前对象的例子
    数组冒泡算法
    java实现星号三角形
    求1到1000之间同时能被3、5、7整除的数
  • 原文地址:https://www.cnblogs.com/feiling/p/3277123.html
Copyright © 2011-2022 走看看