Pascal's Triangle II Leetcode java

题目:

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?

题解

 为了达到O(k)的空间复杂度要求,那么就要从右向左生成结果。相当于你提前把上一行的计算出来,当前行就可以用上一次计算出的结果计算了。

 下面讲解转自Alf的:

“如果没有这个O(k)空间的限制,那么可以一行一行迭代生成。如果要直接生成第i行,假设生成k=3,可以这样考虑这样的一个过程:

1 0 0 0    k = 0

1 1 0 0    k = 1

1 1 1 0

1 2 1 0    k = 2

1 2 1 1

1 2 3 1

1 3 3 1    k = 3

上述过程实际上就是一个in-place的迭代过程。每当生成下一行的时候,首先数组相应位置1,然后从右向左计算每一个系数。


代码如下:

 1     public ArrayList<Integer> getRow(int rowIndex) {  
 2       ArrayList<Integer> result = new ArrayList<Integer>(rowIndex + 1);  
 3       for (int i = 0; i <= rowIndex; i++) {  
 4         result.add(0);  
 5       }  
 6       result.set(0, 1);  
 7       for (int i = 1; i <= rowIndex; i++) {  
 8         result.set(i, 1);  
 9         for (int j = i - 1; j > 0; j--) {  
10           result.set(j, result.get(j) + result.get(j - 1));  
11         }  
12       }  
13       return result;  
14     } 

 Reference:http://blog.csdn.net/abcbc/article/details/8982651

原文地址:https://www.cnblogs.com/springfor/p/3887913.html