leetcode:pascal's_triangle_II

一、     称号

       一行值。

二、     分析

     这道题跟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;
    }
};


版权声明:本文博主原创文章,博客,未经同意不得转载。

posted @ 2015-10-01 12:39  zfyouxi  阅读(165)  评论(0编辑  收藏  举报