zoukankan      html  css  js  c++  java
  • LeetCode 118. Pascal's Triangle

    分析

    难度 易

    来源

    https://leetcode.com/problems/pascals-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]
    ]

    解答

     1 package LeetCode;
     2 
     3 import java.util.ArrayList;
     4 import java.util.List;
     5 
     6 public class L118_PascalTriangle {
     7     public List<List<Integer>> generate(int numRows) {
     8         if(numRows<0)
     9             return null;
    10         List<List<Integer>> result=new ArrayList<List<Integer>>();
    11         List<Integer> list=new ArrayList<Integer>();//记录当前层数值
    12         for(int i=0;i<numRows;i++){
    13             list.add(1);
    14             for(int j=i-1;j>0;j--){//一行一行赋值,对每行从右向左赋值,避免修改下一个数字要用到两个加数
    15                 list.set(j,list.get(j-1)+list.get(j));
    16             }
    17             result.add(new ArrayList<Integer>(list));
    18         }
    19         return result;
    20     }
    21     public static void main(String[] args){
    22         L118_PascalTriangle l118=new L118_PascalTriangle();
    23         System.out.println(l118.generate(5));
    24     }
    25 }

     

    博客园的编辑器没有CSDN的编辑器高大上啊
  • 相关阅读:
    go——数组
    go——流程控制
    go——基本类型
    go——基本构成要素
    go——常量
    go——变量
    go——标准命令
    go——工程结构
    python 优雅的使用正则表达式 ~ 1
    python 安装操作 MySQL 数据库.
  • 原文地址:https://www.cnblogs.com/flowingfog/p/9887397.html
Copyright © 2011-2022 走看看