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

    分析

    难度 易

    来源

    https://leetcode.com/problems/pascals-triangle-ii/

    题目

    Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.

    Note that the row index starts from 0.

     帕斯卡三角形

    In Pascal's triangle, each number is the sum of the two numbers directly above it.

    Example:

    Input: 3
    Output: [1,3,3,1]

    Follow up:

    Could you optimize your algorithm to use only O(k) extra space?

    解答

     1 package LeetCode;
     2 
     3 import java.util.ArrayList;
     4 import java.util.List;
     5 
     6 public class L119_PascalTriangleII {
     7     public List<Integer> getRow(int rowIndex) {
     8         if(rowIndex<0)
     9             return null;
    10         //从0开始的第k行,即(k+1)对应斐波那契数列的最后一行
    11         int listLen=rowIndex+1;
    12         List<Integer> list=new ArrayList<Integer>();//记录当前层数值
    13         for(int i=0;i<listLen;i++)//不知道为什么这句写在这里比下边二层循环的外层快,
    14             list.add(1);//整个都赋1,初试值,各层边界值       
    15         for(int i=0;i<listLen;i++){
    16             for(int j=i-1;j>0;j--){//一行一行赋值,对每行从右向左赋值,避免修改下一个数字要用到两个加数
    17                 list.set(j,list.get(j-1)+list.get(j));
    18             }
    19         }
    20         return list;
    21     }
    22     public static void main(String[] args){
    23         long time1=System.currentTimeMillis();
    24         L119_PascalTriangleII l119=new L119_PascalTriangleII();
    25         System.out.println(l119.getRow(10));//从0开始的第k行,即(k+1)对应斐波那契数列的最后一行
    26         long time2=System.currentTimeMillis();
    27         System.out.println(time2-time1);
    28     }
    29 }

     

    博客园的编辑器没有CSDN的编辑器高大上啊
  • 相关阅读:
    交换机/路由器上的 S口 F口 E口
    对称加密&非对称加密
    字节流和字符流 in Java
    Python中使用MySQL
    完全二叉树、理想二叉树满二叉树
    优化MySchool数据库设计
    关于SQL储存过程中输出多行数据
    关于本月第一天,本月最后一天的SQL代码
    SQL常见的系统存储过程
    相关子查询【SQL Server】
  • 原文地址:https://www.cnblogs.com/flowingfog/p/9895400.html
Copyright © 2011-2022 走看看