码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 119. Pascal's Triangle II

时间:2018-11-02 13:02:18      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:null   int   数字   str   als   []   gif   system   tput   

分析

难度 易

来源

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 }

 

 

LeetCode 119. Pascal's Triangle II

标签:null   int   数字   str   als   []   gif   system   tput   

原文地址:https://www.cnblogs.com/flowingfog/p/9895400.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!