GivennumRows, generate the firstnumRowsof Pascal's triangle.
For example, givennumRows= 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
这是属于基础题目了,记得好像很多基础编程书上都有。
没记错的话,中文名字应该是“杨辉三角”。因为中国人记录这个要早。
本算法用vector保存数据,只保存了有数据的元素,没有保存多余的0.稍微节省点空间吧。
class Solution {
public:
vector<vector<int> > generate(int numRows) {
if(numRows == 0) return vector<vector<int> >(0);
vector<vector<int> > pasVec;
vector<int> preRow, curRow;
int row = 1, col =0;
preRow.push_back(1);
pasVec.push_back(preRow);
for(; row<numRows; row++)
{
curRow.resize(row+1);
for(col = 0; col<=row; col++)
{
passNext(curRow, preRow, row, col);
}
preRow = curRow;
pasVec.push_back(curRow);
}
return pasVec;
}
void passNext(vector<int>& curRow, vector<int>& preRow, int row, int col)
{
if (col==0)
{
curRow[0] = 1;
}
else if (row==col)
{
curRow[col] = 1;
}
else
{
curRow[col] = preRow[col]+preRow[col-1];
}
}
};
//2014-2-17 update
vector<vector<int> > generate(int numRows)
{
if (numRows < 1) return vector<vector<int> >();
vector<vector<int> > rs(1, vector<int>(1,1));
for (int i = 1; i < numRows; i++)
{
rs.push_back(vector<int>(1,1));
for (int j = 1; j < i; j++)
{
rs.back().push_back(rs[i-1][j-1] + rs[i-1][j]);
}
rs.back().push_back(1);
}
return rs;
}
杨辉三角生成算法
本文介绍了一种使用C++实现的杨辉三角生成算法。该算法通过vector容器存储每行的数据,有效地避免了存储多余0的情况,从而节省了内存空间。文章提供了两种不同的实现方式,并详细解释了其工作原理。
801

被折叠的 条评论
为什么被折叠?



