【LeetCode】118_Pascal's Triangle
2015-08-19 20:29
323 查看
题目
Pascal'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] ]
解析
很简单,下一行第j元素用上一行相同的位置和前一个位置的和即可。需要注意的就是两边都是1直接上代码
class Solution { public: vector<vector<int>> generate(int numRows){ vector<vector<int>> ret; for (int i = 0;i<numRows;i++) { vector<int> tmp(i+1); tmp[0] = 1; tmp[i] = 1; for (int j = 1;j<i;j++) { tmp[j] = ret[i-1][j]+ret[i-1][j-1]; } ret.push_back(tmp); } return ret; } };
方法挺简单的,可以优化的地方在于其实他是左右对称的,没必要把一行全计算一遍。
看看大神的代码
从左到右
class Solution { public: vector<vector<int>> generate(int numRows){ vector<vector<int> > result; if(numRows == 0) return result; result.push_back(vector<int>(1,1)); //first row for(int i = 2; i <= numRows; ++i) { vector<int> current(i,1); // 本行 const vector<int> &prev = result[i-2]; // 上一行 for(int j = 1; j < i - 1; ++j) { current[j] = prev[j-1] + prev[j]; // 左上角和右上角之和 } result.push_back(current); } return result; } };
从右到左
class Solution { public: vector<vector<int>> generate(int numRows){ vector<vector<int> > result; vector<int> array; for (int i = 1; i <= numRows; i++) { for (int j = i - 2; j > 0; j--) { array[j] = array[j - 1] + array[j]; } array.push_back(1); result.push_back(array); } return result; } };
相关文章推荐
- POJ 1426 Find The Multiple (DFS / BFS)
- 详略。。设计模式1——单例。。。。studying
- 有感,懂市场比懂产品重要,懂产品比懂技术重要——想起凡客诚品和YY语音了
- map的使用方法
- FZUOJ 过河I (BFS 好题)
- 再谈js拖拽(二)仿iGoogle自定义首页模块拖拽
- 参加北京bluemix云计算大会偶记
- 取消360安全卫士开机自启动
- bzoj 2818 Gcd(莫比乌斯+gcd(a,b)=d) 经典
- PostgreSQL Replication之第一章 理解复制概念(3)
- 个人--20140711 转正定级 个人工作总结
- 关键字输入框js
- 四大开源3d游戏引擎探究----irrlicht与orge对比
- 再谈js拖拽(一)
- [Objective-C]关联(objc_setAssociatedObject、objc_getAssociatedObject、objc_removeAssociatedObjects)
- WCF 无法激活服务,因为它不支持 ASP.NET 兼容性。已为此应用程序启用了 ASP.NET 兼容性
- 锲而不舍,学有大成
- WCF 无法激活服务,因为它不支持 ASP.NET 兼容性。已为此应用程序启用了 ASP.NET 兼容性
- 解密
- 前端开发必须知道的JS(二) 闭包及应用