LEETCODE--Pascal's Triangle II
2015-11-12 10:27
288 查看
Given an index k, return the kth row of the Pascal’s triangle.
For example, given k = 3,
Return [1,3,3,1].
Note:
Could you optimize your algorithm to use only O(k) extra space?
Subscribe to see which companies asked this question
方法一:
从后往前进行加法赋值;
方法二:
For example, given k = 3,
Return [1,3,3,1].
Note:
Could you optimize your algorithm to use only O(k) extra space?
Subscribe to see which companies asked this question
方法一:
从后往前进行加法赋值;
class Solution { public: vector<int> getRow(int rowIndex) { vector<int> A; A.push_back(1); if(rowIndex == 0) return A; A.push_back(1); if(rowIndex == 1) return A; for(int x = 2; x <= rowIndex; x++){ A.push_back(0); } for(int i = 2; i <= rowIndex; i++){ A[i] = 1; for(int j = i-1; j > 0; j--){ A[j] = A[j] + A[j-1]; } A[0] = 1; } return A; } };
方法二:
class Solution { public: vector<int> getRow(int rowIndex) { vector<vector<int>> finsh; vector<int> last; vector<int> add; finsh.push_back(add); finsh[0].push_back(1); rowIndex += 1; if(rowIndex == 1) return finsh[0]; else{ for(int i = 1; i < rowIndex; i++){ if(i == finsh.size()) { vector<int> add; finsh.push_back(add); } finsh[i].push_back(1); for(int j = 1; j <= i; j++){ if(finsh[i].size() == i) finsh[i].push_back(1); else{ int x = finsh[i-1][j-1]; int y = finsh[i-1][j]; int elem = x + y; finsh[i].push_back(elem); } } } return finsh[rowIndex-1]; } } };
相关文章推荐
- Opencv 人脸识别
- webrtc 相关标准
- js中的特有语句with和 for in
- HibernateTemplate、HibernateDaoSupport两种方法实现增删改查
- 【数据结构】堆
- 利用Notepad++插件(JSToolNpp):让JS代码格式化对齐
- 关于c#webform 通用变量的几种办法
- paint.setTypeface(Typeface.DEFAULT_BOLD);
- Google分布式系统三大论文(三)MapReduce: Simplified Data Processing on Large Clusters
- TCP/IP、Http、Socket的区别
- 034 - Search for a Range
- c++分数类
- AFNetWorking 同步异步请求
- html中常见的一些字符实体
- HTML5 自定义属性 data-* 和 jQuery.data 详解
- JVM-GC算法_复制算法&&标记/整理算法
- 关于ie6,ie7,ie8,firefox 的div兼容问题
- 用gdb调试程序笔记: 以段错误(Segmental fault)为例
- jquery的extend和fn.extend (扩展jQuery类或jQuery对象方法)
- Listview下方的Button随着Item滑动