LeetCode(Oct 29 '12):Pascal's Triangle II
2013-07-02 10:42
260 查看
题目地址:http://leetcode.com/onlinejudge#question_119
题目要求:
分析:要求在O(n)的空间内获得第k+1行的帕斯卡尔三角形的值。
假设三角形存在二维数组Data中,其组织形式如下:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
有以下特征:
Data[i][0]和Data[i][i]的值均为1
Data[i][m]=Data[i-1][m-1]+Data[i-1][m]
观察以上规律,发现在一维数组中,逆向求解,不会破坏后续计算所需要的数值。
代码如下:
另外尝试用了一下流迭代器输出vector的元素,
要注意迭代器的type和vector的type匹配
代码如下:
题目要求:
分析:要求在O(n)的空间内获得第k+1行的帕斯卡尔三角形的值。
假设三角形存在二维数组Data中,其组织形式如下:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
有以下特征:
Data[i][0]和Data[i][i]的值均为1
Data[i][m]=Data[i-1][m-1]+Data[i-1][m]
观察以上规律,发现在一维数组中,逆向求解,不会破坏后续计算所需要的数值。
代码如下:
class Solution { public: vector<int> getRow(int rowIndex) { rowIndex++; vector<int> tmp; if(rowIndex==0) return tmp; tmp.assign(rowIndex,0); tmp[0]=1; for(int i=2;i<=rowIndex;i++) { for(int n=i;n>=2;n--) { if(n==i) { tmp[n-1]=1; continue; } tmp[n-1]=tmp[n-1]+tmp[n-2]; } } return tmp; } };
另外尝试用了一下流迭代器输出vector的元素,
要注意迭代器的type和vector的type匹配
代码如下:
ostream_iterator<int> output(cout," "); copy(tmp.begin(),tmp.end(),output);
相关文章推荐
- LeetCode(Oct 19 '12):Distinct Subsequences
- LeetCode(Oct 28 '12):Pascal's Triangle
- LeetCode118 Pascal's Triangle
- 如何解决Error: Can't create a new thread (errno 12)
- LeetCode - Pascal's Triangle I && II
- Leetcode Pascal's Triangle
- [*leetcode 39] Combination Sum && [*leetcode 40] Combination Sum II
- 【LeetCode】118_Pascal's Triangle
- Jack's Notes12——全选、全不选、反选(循环遍历给按钮动态注册事件)
- 89.You need to display the date 11-oct-2007 in words as 'Eleventh of October, Two Thousand Seven'.
- LeetCode(Oct28'12):Populating Next Right Pointers in Each Node
- LeetCode: Pascal's Triangle [118]
- LeetCode 39 && 40 Combination Sum I && II 关键在于剪枝,剪枝讨论在末尾
- Pascal's Triangle -- leetcode
- leetcode:Pascal's Triangle
- leetcode Pascal's Triangle II
- Pascal's Triangle -- LeetCode
- BestCoder Round#29 1001 GTY's math problem
- Leetcode Pascal's Triangle
- Leetcode Pascal's Triangle