Leetcode-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]
]

分析:打印杨辉三角。numRows=0 或者 numRows=1时特殊处理。

numRows>=2时都是有规律的了。


代码例如以下:

#include <iostream>
#include <vector>

using namespace std;

vector<vector<int> > generate(int numRows)
{
	vector<vector<int> > res;
	vector<int> currentRow;
	vector<int> lastRow;
	if(numRows <= 0)
		return res;
	currentRow.push_back(1);
	res.push_back(currentRow);
	if (numRows == 1)
		return res;

	for (int i=0; i<numRows-1; i++)
	{
		lastRow = currentRow;
		currentRow.clear();
		currentRow.push_back(1);
		for(int j=0; j<lastRow.size()-1; j++)
			currentRow.push_back(lastRow[j] + lastRow[j+1]);
		currentRow.push_back(1);
		res.push_back(currentRow);
	}
	return res;
}

int _tmain(int argc, _TCHAR* argv[])
{
	vector<vector<int> > res = generate(5);

	// 打印结果
	for (int i=0; i<res.size(); i++)
	{
		vector<int> row = res[i];
		for (int j=0; j<row.size(); j++)
			cout << row[j] <<" ";
		cout << endl;
	}

	return 0;
}







posted on 2019-04-08 18:10  xfgnongmin  阅读(96)  评论(0编辑  收藏  举报

导航