题目描述:

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? 

和上一题一样,同样是要我们返回一个杨辉(帕斯卡)三角,不过这题要我们返回的是某一行的一维数组。

Note:能否让你的代码优化成只使用O(k)额外空间?

解题思路:

思路还是和上一题一样,只要记住杨辉三角的每行的第n个数是上一行的两个数第n,n-1个数之和就行了。这题我同样用的是递归的方法。

代码:

 1 class Solution {
 2 public:
 3     vector<int> getRow(int rowIndex) {
 4         vector<int> result;
 5         if(rowIndex==0){
 6             result.push_back(1);
 7             return result;
 8         }
 9         result=getRow(rowIndex-1);
10         result.push_back(0);
11         for(int i=rowIndex;i>=0;i--)
12             result[i]+=result[i-1];
13         return result;
14     }
15 };

 

他人代码:

 1 class Solution {
 2 public:
 3     vector<int> getRow(int rowIndex) {
 4     //这是迭代的方法,思路还是一样
 5         vector<int> res(rowIndex+1,0);
 6         res[0] = 1;
 7         for(int i=1;i<rowIndex+1;++i) {
 8             for(int j=i;j>=1;--j) {
 9                 res[j] += res[j-1];
10             }
11         }
12         return res;
13     }
14 };

 

 

 

 

posted on 2018-02-11 22:22  宵夜在哪  阅读(73)  评论(0编辑  收藏  举报