菱纱梦

导航

Pascal's Triangle II <leetcode>

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?

 

算法:根据帕斯卡三角形的规律直接求,比较简单,可能有其他好的方法,代码如下:

 

 1 class Solution {
 2 public:
 3     vector<int> getRow(int rowIndex) {
 4         vector<int>  temp(rowIndex+1);
 5         vector<int>  pre(rowIndex+1);
 6         pre[0]=1;
 7         for(int i=0;i<=rowIndex;i++)
 8         {
 9             temp[0]=1;
10             temp[i]=1;
11             for(int j=1;j<i;j++)
12             {
13                 temp[j]=pre[j-1]+pre[j];
14             }
15             pre=temp;
16         }
17         return temp;
18     }
19 };

 

posted on 2014-09-09 10:58  菱纱梦  阅读(116)  评论(0编辑  收藏  举报