[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 };
posted @ 2012-11-13 11:44  chkkch  阅读(3276)  评论(0编辑  收藏  举报