118. Pascal's Triangle 杨辉三角
2017-05-02 16:53
309 查看
118. Pascal's Triangle
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
按照规律写两个循环即可,但是要注意新值覆盖旧值的问题,而且只能计算一半,剩下一半对称复制。
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<int> happy;
vector<vector<int>> res;
if(numRows==0) return res;
happy.push_back(1);
res.push_back(happy);
if(numRows==1) return res;
happy.push_back(1);
res.push_back(happy);
if(numRows==2) return res;
for(int i=3;i<=numRows;i++)
{
for(int j=(happy.size())/2;j>=1;j--)//这个循环要从大到小
{
happy[j]=happy[j]+happy[j-1];
happy[happy.size()-j]=happy[j];
}
happy.push_back(1);
res.push_back(happy);
}
return res;
}
};
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] ]
按照规律写两个循环即可,但是要注意新值覆盖旧值的问题,而且只能计算一半,剩下一半对称复制。
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<int> happy;
vector<vector<int>> res;
if(numRows==0) return res;
happy.push_back(1);
res.push_back(happy);
if(numRows==1) return res;
happy.push_back(1);
res.push_back(happy);
if(numRows==2) return res;
for(int i=3;i<=numRows;i++)
{
for(int j=(happy.size())/2;j>=1;j--)//这个循环要从大到小
{
happy[j]=happy[j]+happy[j-1];
happy[happy.size()-j]=happy[j];
}
happy.push_back(1);
res.push_back(happy);
}
return res;
}
};
相关文章推荐
- Leetcode - Array - 118. Pascal's Triangle(杨辉三角)
- 杨辉三角(Pascal's Triangle)- LeetCode118-119
- LeetCode-118:Pascal's Triangle (生成指定行数的杨辉三角)
- Leetcode#118. Pascal's Triangle(杨辉三角I)
- 118. Pascal's Triangle (杨辉三角)
- [leetCode 118 & 119] Pascal's Triangle I && II (杨辉三角问题)
- 118. Pascal's Triangle&&119. Pascal's Triangle II
- 118. Pascal's Triangle
- 118. Pascal's Triangle
- [leetcode, python] Pascal's Triangle II 杨辉三角
- 118. Pascal's Triangle
- [3]118. Pascal's Triangle(Java)
- 2017.11.14 LeetCode - 118. Pascal's Triangle - 119. Pascal's Triangle II
- 118. Pascal's Triangle
- <LeetCode><Easy> 118 Pascal's Triangle II
- LeetCode OJ 系列之118 Pascal's Triangle --Python
- LeetCode 118, 119. Pascal's Triangle i, ii
- 118.Pascal's Triangle
- 【一天一道LeetCode】#118. Pascal's Triangle
- LeetCode笔记:118. Pascal's Triangle