[LeetCode] 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?

對於產生一個新的行用從后往前的方法來更新,這樣就只需一個O(k)的空間。

 1 class Solution {
 2 public:
 3     vector<int> getRow(int rowIndex) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         vector<int> a(rowIndex + 1);
 7         
 8         a[0] = 1;
 9         for(int i = 1; i <= rowIndex; i++)
10             for(int j = i; j >= 0; j--)
11                 if (j == i)
12                     a[j] = a[j-1];
13                 else if (j == 0)
14                     a[j] = a[j];
15                 else
16                     a[j] = a[j-1] + a[j];
17                     
18         return a;                    
19     }
20 };


免責聲明!

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



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