LeetCode 119. Pascal's Triangle II (杨辉三角之二)

Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,
Return [1,3,3,1].

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


题目标签:Array

  这道题目与之前那题不同的地方在于,之前是给我们一个行数n,让我们把这几行的全部写出来,这样就可以在每写新的一行的时候根据之前的那一行来得出。这一题给了我们一个k,让我们直接得出第3行的数字(这里从0开始,所以3代表第四行)。我们可以先设一个list size为 k + 1。然后把k + 1 的0加入list。 接着设第一个位置为1,之后遍历剩下的数字,对于每一个数字,把它设为1,并且遍历这个数字的前一个数字,一直回到最开始的第二个数字,对于每一个数字,把它和它前面一个相加。(这一步就等于把之前的每一行给重现出来)。我们来看一个例子:

当k = 4,

0  0  0  0  0  先设5个0

1  0  0  0  0  第一个设为1

1  1  0  0  0  第二个设为1

1  1  1  0  0  第三个数字设为1的时候,就需要开始遍历前面一个数字了,因为第二个数字1 position 为1 > 0

1  2  1  0  0    遍历完之后的结果

1  2  1  1  0  第四个数字设为1的时候,需要开始遍历从前面一个数字,一直回到第二个数字

1  2  3  1  0    遍历中

1  3  3  1  0    遍历结束

1  3  3  1  1  第五个数字设为1, 从第四个遍历回第二个

1  3  3  4  1    遍历中

1  3  6  4  1    遍历中

1  4  6  4  1    遍历结束,得到答案

Java Solution:

Runtime beats 51.88% 

完成日期:04/06/2017

关键词:Array

关键点:设k+1个0,设第一个为1,遍历之后的数字,把每一个数字设为1的同时,从前一个数字遍历回第二个数字,生成新一行的数组

 1 public class Solution 
 2 {
 3    public ArrayList<Integer> getRow(int rowIndex) 
 4    {  
 5       // define arraylist with size = rowIndex + 1.
 6         ArrayList<Integer> result = new ArrayList<Integer>(rowIndex + 1);  
 7          
 8         // first, add all 0s for each spot.
 9         for(int i = 0; i <= rowIndex; i++)  
10             result.add(0);  
11         
12         // set the first number to 1.
13         result.set(0, 1); 
14          
15         // iterate from second number to end
16         for(int i = 1; i <= rowIndex; i++) 
17         {
18             // set the number to 1 first.
19             result.set(i, 1);  
20             // iterate from the prior number to 2nd number (backward).
21             for(int j = i - 1; j > 0; j--) 
22                 result.set(j, result.get(j) + result.get(j - 1));// update the number with sum of itself and prior one.  
23             
24         }  
25         
26         
27         return result;  
28     }
29 }

参考资料:

http://www.cnblogs.com/springfor/p/3887913.html

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

原文地址:https://www.cnblogs.com/jimmycheng/p/7439965.html