首页 > 其他 > 详细

LeetCode 118:Pascal's Triangle

时间:2015-06-06 09:08:55      阅读:210      评论:0      收藏:0      [点我收藏+]

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

题目要求计算杨辉三角,代码如下:

class Solution {
public:
    vector<vector<int> > generate(int numRows) {
       vector< vector<int> >result;
		if (numRows<= 0)
			return result;

		for (int i=1; i<=numRows; i++){
			vector<int> *tmp = new vector<int>();
			tmp->push_back(1);
			if (i == 1)
			{
				result.push_back(*tmp);
				continue;
			}
			vector<int> prev = result[i-2]; 
			for (int j=0; j<i-2; j++)
			{
				tmp->push_back(prev[j]+prev[j+1]);
			}
			tmp->push_back(1);
			result.push_back(*tmp);
		}

		return result; 
    }
};


LeetCode 118:Pascal's Triangle

原文:http://blog.csdn.net/sunao2002002/article/details/46384253

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!