您的位置:首页 > 其它

leetcode:pascal's_triangle_II

2014-10-24 16:28 183 查看
一、     题目

       这道题是要求得杨辉三角的某一行值。

二、     分析

     这道题跟Pascal'sTriangle很类似,只是这里只需要求出某一行的结果。Pascal's Triangle中因为是求出全部结果,所以我们需要上一行的数据就很自然的可以去取。而这里我们只需要一行数据,就得考虑一下是不是能只用一行的空间来存储结果而不需要额外的来存储上一行呢?

    这里确实是可以实现的。对于每一行我们知道如果从前往后扫,第i个元素的值等于上一行的ans[i]+ans[i+1],可以看到数据是往前看的,如果我们只用一行空间,那么需要的数据就会被覆盖掉。所以这里采取的方法是从后往前扫,这样每次需要的数据就是ans[i]+ans[i-1],我们需要的数据不会被覆盖,因为需要的ans[i]只在当前步用,下一步就不需要了。这个技巧在动态规划省空间时也经常使用,主要就是看我们需要的数据是原来的数据还是新的数据来决定我们遍历的方向。时间复杂度还是O(n^2),而空间这里是O(k)来存储结果,仍然不需要额外空间。

     例如:当行数为5时

          0  :   0 00 0 0

          1  :   1
00 0 0

          2  :   1 10 0 1

          3  :   1 21 0 1

          4  :   1 33 1 1

          5  :   1 46 4 1

   可知红色部分为标准的杨辉三角,所以不难理解从后往前的遍历方式。

class Solution {
public:
vector<int> getRow(int rowIndex) {
if (rowIndex < 0) return vector<int>();
vector<int> res(rowIndex + 1);
if (rowIndex == 0)
{
res[0] = 1;
return res;
}

int t1, t2;

for (int i = 1; i <= rowIndex; i++)
{
res[0] = res[i] = 1;
t1 = res[0];
t2 = res[1];
for (int j = 1; j < i; j++)
{
res[j] = t1 + t2;
t1 = t2;
t2 = res[j + 1];
}
}
return res;
}
};

class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> ans(rowIndex+1,1);
for(int i=0;i<=rowIndex;i++) {
for(int j=i-1;j>=1;j--) {
ans[j]=ans[j]+ans[j-1];
}
}
return ans;
}
};

class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> ans;
if(rowIndex <0) return ans;
ans.push_back(1);
for(int i=1;i<=rowIndex;i++) {
for(int j=ans.size()-2;j>=0;j--) {
ans[j+1]=ans[j]+ans[j+1];
}
ans.push_back(1);
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息