码迷,mamicode.com
首页 > 其他好文 > 详细

Pascal's Triangle II

时间:2015-04-13 12:20:33      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:

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?

 

Hide Tags
 Array
 

 

方法一:保存所有二位数组

class Solution {
    public:
        vector<int> getRow(int rowIdx) {
            vector<int> curLine;
            vector<vector<int> >  res;
            curLine.push_back(1);
            res.push_back(curLine);
            if( rowIdx == 0)
                return curLine;

            for(int i = 1; i <= rowIdx; i++)
            {
                curLine.clear();
                for(int j = 0; j < res[i-1].size(); j++)
                {
                    if(j == 0)
                        curLine.push_back(1);
                    else
                        curLine.push_back(res[i-1][j-1] + res[i-1][j]);
                }
                curLine.push_back(1);
                res.push_back(curLine);
            }
            return res[rowIdx];
        }
};

 

方法二:cur只和上一行有关,用滚动数组即可实现空间复杂度O(n)

class Solution {
    public:
        vector<int> getRow(int rowIdx) {
            vector<int> preLine;
            vector<int> curLine;

            curLine.push_back(1);

            if(rowIdx == 0)
                return curLine;

            for(int i = 1; i <= rowIdx; i++)
            {
                preLine = curLine;
                curLine.clear();

                for(int j = 0; j < preLine.size(); j++)
                {
                    if(j == 0)
                        curLine.push_back(1);
                    else
                        curLine.push_back(preLine[j-1] + preLine[j]);

                }
                curLine.push_back(1);
            }
            return curLine;
        }
};

 

Pascal's Triangle II

标签:

原文地址:http://www.cnblogs.com/diegodu/p/4421725.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!