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

 这是属于基础题目了,记得好像很多基础编程书上都有。

没记错的话,中文名字应该是“杨辉三角”。因为中国人记录这个要早。

本算法用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;
	}

 

 

你可能感兴趣的:(LeetCode,杨辉三角,Pascals,Triangle)