[LeetCode]118. Pascal's Triangle
程序员文章站
2024-02-20 23:25:46
...
[LeetCode]118. Pascal’s Triangle
题目描述
思路
水题,根据前数组计算当前数组
代码
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> generate(int numRows) {
/*
vector<vector<int>> res;
for (int i = 0; i < numRows; ++i) {
vector<int> temp;
if (i < 2)
for (int j = 0; j <= i; ++j)
temp.push_back(1);
else {
int left = 0, right = 1;
for (int j = 0; j <= i; ++j) {
if (j == 0 || j == i)
temp.push_back(1);
else
temp.push_back(res[i - 1][left++] + res[i - 1][right++]);
}
}
res.push_back(temp);
}
return res;
*/
vector<vector<int>> res(numRows);
for (int i = 0; i < numRows; ++i) {
res[i].resize(i + 1);
res[i][0] = 1;
res[i][i] = 1;
for (int j = 1; j < i; ++j) {
res[i][j] = res[i - 1][j - 1] + res[i - 1][j];
}
}
return res;
}
};
int main() {
vector<vector<int>> res;
Solution s;
res = s.generate(5);
for (auto vec : res) {
for (int num : vec)
cout << num << " ";
cout << endl;
}
system("pause");
return 0;
}
上一篇: Android单点触控实现图片平移、缩放、旋转功能
下一篇: Android 判断是否有外网连接
推荐阅读
-
[LeetCode]118. Pascal's Triangle
-
Leetcode No.119 Pascal's Triangle II(c++实现)
-
杨辉三角(pascal's triangle)
-
LeetCode-119. Pascal's Triangle II
-
119. Pascal's Triangle II [杨辉三角形2]
-
119. Pascal's Triangle II
-
leetcode -- 119. Pascal's Triangle II
-
2018.05.03 leetcode #119. Pascal's Triangle II
-
【leetcode】119. Pascal's Triangle II
-
LeetCode 119. Pascal's Triangle II