现在的位置: 首页 > 综合 > 正文

Pascal’s Triangle、Pascal’s Triangle II

2017年12月23日 ⁄ 综合 ⁄ 共 932字 ⁄ 字号 评论关闭

Pascal's
Triangle:

Given numRows, generate the first numRows of
Pascal's triangle.

For example, given numRows = 5,

Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]
class Solution {
public:
    vector<vector<int> > generate(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        

    	if ( n<=0 )
			return vector<vector<int> >();
		vector<int> level;
		vector<vector<int> > ret;
		for(int i=1;i<=n;i++)
		{
			int k=(int)level.size();
			for(int  j=k-1;j>=1;j--)
				level[j]+=level[j-1];
			level.push_back(1);
			ret.push_back(level);
		}
		return ret;
    }
};

Pascal's
Triangle II:

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?

class Solution {
public:
    vector<int> getRow(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        if ( n<0 )
    		return vector<int>();
		vector<int> level;
		for(int i=0;i<=n;i++)
		{
			int k=(int)level.size();
			for(int  j=k-1;j>=1;j--)
				level[j]+=level[j-1];
			level.push_back(1);
		}
		return level;
    }
};

抱歉!评论已关闭.