Pascal's Triangle、Pascal's Triangle II

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 > generate(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        

    	if ( n<=0 )
			return vector >();
		vector level;
		vector > 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 getRow(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        if ( n<0 )
    		return vector();
		vector 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;
    }
};


你可能感兴趣的:(LeetCode)