LeetCode 119. Pascal's Triangle II
Posted flowingfog
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }
以上是关于LeetCode 119. Pascal's Triangle II的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 119. Pascal's Triangle II
LeetCode 119. Pascal's Triangle II
C#解leetcode:119. Pascal's Triangle II
Java [Leetcode 119]Pascal's Triangle II