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的编辑器高大上啊
  • 相关阅读:
    java学习网址大全
    Js 提示框
    api帮助文档及常见IT学习网站
    传参给 jsp
    jsp>action
    二级横菜单显示+sitemesh母板应用
    request,session
    map>json
    清空image画布并改变大小填充背景色
    取汉字首字母方法
  • 原文地址:https://www.cnblogs.com/flowingfog/p/9895400.html
Copyright © 2011-2022 走看看