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
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....
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; } }
相关文章推荐
- 网格布局 计算器
- 【代码笔记】iOS-UIScrollerView里有两个tableView
- 软件开发公司必须具备的环境软件
- 需求驱动还是技术驱动,大跃进的聊天机器人在开着一辆往历史倒退的车
- 从头开始学习
- String,StringBuffer与StringBuilder的区别??
- 知道这20个正则表达式,能让你少写1,000行代码
- Java多线程学习(吐血超详细总结)
- socket、http、tcp
- JQuery-layer web弹窗层
- 2016年3月AV评测
- Oracle数据库存储过程使用中一些注意事项
- 关于Android创建Activity需要注意的地方
- footer元素
- 计蒜课 挑战难题 组合运算式
- iOS 获得当前的版本号app等详解
- 中国广电将成第四运营商
- Mongodb aggregate group DBRef类型,并处理返回的DBRef数据Demo
- js显示世界时间示例(包括世界各大城市)
- 拉普拉斯锐化处理