leetcode_118题——Pascal's Triangle(简单的数学题)

Pascal's Triangle

  Total Accepted: 43845 Total Submissions: 145271My Submissions

 

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]

]

 

 

Hide Tags
  Array
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

     这道题是一个简单的数学题,第n+1行的数由第n行的数来计算,即最前最后为1,其他的数依次由n行的第i和第i+1个数相加而得

#include<iostream>

#include <vector>

using namespace std;





vector<vector<int>> generate(int numRows) {

	vector<int> temp1;

	vector<int> temp2;

	vector<vector<int> >templast;

	if(numRows==0)

		return templast;

	if(numRows==1)

	{

		temp1.push_back(1);

		templast.push_back(temp1);

		return templast;

	}

	if(numRows==2)

	{

		temp1.push_back(1);

		templast.push_back(temp1);

		temp1.push_back(1);

		templast.push_back(temp1);

		return templast;

	}



	temp1.push_back(1);

	templast.push_back(temp1);//第一行

	temp2.push_back(1),temp2.push_back(1);

	templast.push_back(temp2);//第二行



	for(int i=2;i<numRows;i++)

	{

		temp1.clear();

		int len=temp2.size();

		temp1.push_back(1);

		for(int i=0;i<len-1;i++)

			temp1.push_back(temp2[i]+temp2[i+1]);

		temp1.push_back(1);

		templast.push_back(temp1);

		temp2.clear();

		temp2=temp1;

	}

	return templast;

}

int main()

{

	vector<vector<int> > vec1;

	vec1=generate(5);



	int len_n=vec1.size();



	for(int i=0;i<len_n;i++)

	{

		int len_m=vec1[i].size();

		for(int j=0;j<len_m;j++)

			cout<<vec1[i][j]<<' ';

		cout<<endl;

	}



}

  

你可能感兴趣的:(LeetCode)