leetcode118Pascal'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]
去年刚学编程的时候,第一本书谭浩强的C程序设计里就有这杨一个杨辉三角的题,可是年代久远,,,已经遗忘了,,,这次遇到,居然不会做。。。怒百度。。。好了,容我将方法自己阐述一遍,加强印象。
首先创建一个数组,里面放个1,然后从第二层开始,给数组尾部添个0,然后赋给另外一个数组,遍历新的数组,从下标1开始,新数组该下标上的值为原来数组中该位置以及该位置之前的2个值的和,依次类推,循环往复。
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> result;
if (numRows <= 0)
{
return result;
}
vector<int> temp(1, 1);
result.push_back(temp);
for (int i = 2; i <= numRows; ++i)
{
temp.push_back(0);
vector<int> t = temp;
for (int j = 1; j < i; ++j)
{
t[j] = temp[j] + temp[j-1];
}
result.push_back(t);
temp = t;
}
return result;
}
};