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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM