118. Pascal's Triangle
2017-06-19 12:41
369 查看
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
思路:杨辉三角 很简单的逻辑判断 但看了某大神的代码 还是有的不小的差距 在时间上和简洁度上
C++代码:
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> res;
vector<int> btemp;
if(numRows==0)
return res;
btemp.push_back(1);
res.push_back(btemp);
if(numRows==1){
return res;
}
for(int i=2;i<=numRows;i++){
vector<int> temp;
for(int j=0;j<i;j++){
if(j==0||j==i-1)
temp.push_back(1);
else
temp.push_back(btemp[j-1]+btemp[j]);
}
btemp.clear();
btemp = temp;
res.push_back(temp);
}
return res;
}
};大神的代码:简单明了 得多学习下代码的简洁了
class Solution {
public:
vector<vector<int> > generate(int numRows) {
vector<vector<int>> r(numRows);
for (int i = 0; i < numRows; i++) {
r[i].resize(i + 1);
r[i][0] = r[i][i] = 1;
for (int j = 1; j < i; j++)
r[i][j] = r[i - 1][j - 1] + r[i - 1][j];
}
return r;
}
};
For example, given numRows = 5,
Return
[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
思路:杨辉三角 很简单的逻辑判断 但看了某大神的代码 还是有的不小的差距 在时间上和简洁度上
C++代码:
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> res;
vector<int> btemp;
if(numRows==0)
return res;
btemp.push_back(1);
res.push_back(btemp);
if(numRows==1){
return res;
}
for(int i=2;i<=numRows;i++){
vector<int> temp;
for(int j=0;j<i;j++){
if(j==0||j==i-1)
temp.push_back(1);
else
temp.push_back(btemp[j-1]+btemp[j]);
}
btemp.clear();
btemp = temp;
res.push_back(temp);
}
return res;
}
};大神的代码:简单明了 得多学习下代码的简洁了
class Solution {
public:
vector<vector<int> > generate(int numRows) {
vector<vector<int>> r(numRows);
for (int i = 0; i < numRows; i++) {
r[i].resize(i + 1);
r[i][0] = r[i][i] = 1;
for (int j = 1; j < i; j++)
r[i][j] = r[i - 1][j - 1] + r[i - 1][j];
}
return r;
}
};
相关文章推荐
- 118. Pascal's Triangle
- 118. Pascal's Triangle
- 118. Pascal's Triangle (杨辉三角)
- 118. Pascal's Triangle
- leetcode 118|119. Pascal's Triangle 1|2
- 118, 119Pascal's Triangle
- <LeetCode><Easy> 118 Pascal's Triangle
- [LeetCode-118] Pascal's Triangle(帕斯卡三角形)
- 【leetcode】【118】Pascal's Triangle
- 118. Pascal's Triangle 简单数组问题
- 118. Pascal's Triangle
- [LeetCode] 118. Pascal's Triangle
- [LeetCode]--118. Pascal's Triangle
- 118. Pascal's Triangle
- 118. Pascal's Triangle
- 118. Pascal's Triangle
- 118. Pascal's Triangle
- 118. Pascal's Triangle
- LeetCode(118) Pascal's Triangle (Java)
- LeetCode 118, 119. Pascal's Triangle i, ii