LeetCode Pascal's Triangle 打印杨辉三角

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;
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值