您的位置:首页 > 其它

LeetCode 118. Pascal's Triangle

2016-04-22 09:11 387 查看
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]
]

Just need to find the rule.

The first one is {1}, second one is {1, 1}. Start from 3rd one, there is a rule:

Suppose the 3rd one, we push into {1, 1, 1} which is 2ed one append one more 1. But we need to change 1 into 2. It just needs 1 + 1 --- Not clear enough? go one more then.

Suppose the 4th one, we push into {1, 2, 1, 1} which is 3rd one append one more 1. we can just make res[3][1] += res[2][0] and then res[3][2] += res[2][1]

Suppose the 5th one, we push into {1, 3, 3, 1, 1} which is 4th one append one more 1. then, change res[4][1] += res[3][0], res[4][2] += res[3][1]; res[4][3] += res[3][2]

so on and so forth....

#include <vector>
#include <iostream>
using namespace std;

vector< vector<int> > generate(int numRows) {
if(numRows <= 0) return {};
vector< vector<int> > res;
res.push_back({1});
for(int i = 2; i <= numRows; ++i) {
vector<int> tmp = res.back();
tmp.push_back(1);
res.push_back(tmp);
if(res.size() >= 3) {
for(int j = 1; j < res[i - 1].size() - 1; ++j) {
res[i - 1][j] += res[i-2][j - 1];
}
}
}
return res;
}

int main(void) {
vector< vector<int> > res = generate(5);
for(int i = 0; i < res.size(); ++i) {
for(int j = 0; j < res[i].size(); ++j) {
cout << res[i][j] << " ";
}
cout << endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: