Pascal's Triangle Solutions in C++
Number 118
Difficulty Easy
Acceptance 52.6%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/pascals-triangle/// Author : Hao Chen// Date : 2014-06-18#include <stdlib.h>#include <vector>#include <iostream>using namespace std;vector<vector<int> > generate(int numRows){vector<vector<int> > pascalTriangle;for (int i=0; i<numRows; i++){vector<int> v;if (i==0){v.push_back(1);} else {v.push_back(1);for(int j=0; j<pascalTriangle[i-1].size()-1; j++){v.push_back(pascalTriangle[i-1][j] + pascalTriangle[i-1][j+1]);}v.push_back(1);}pascalTriangle.push_back(v);}return pascalTriangle;}void printTriangle(vector< vector<int> > pt){cout << "[" << endl;for(int i=0; i<pt.size(); i++){for(int space=(pt.size()-i-1); space>=0; space--){cout << " ";}cout << "[";for(int j=0; j<pt[i].size(); j++){cout << pt[i][j];if(j<pt[i].size()-1){cout << ",";}}cout << "]";if(i<pt.size()-1){cout << ",";}cout << endl;}cout << "]" << endl;}int main(int argc, char** argv){int n = 3;if (argc>1) {n = atoi(argv[1]);}printTriangle(generate(n));}
C++ solution by pezy/LeetCode
#include <vector>using std::vector;class Solution {public:vector<vector<int> > generate(int numRows) {vector<vector<int> > vec;for (int i=0; i<numRows; ++i) {vector<int> row;if (!vec.empty()) row.assign(vec.at(i-1).begin(), vec.at(i-1).end());row.push_back(1);for (int j=i-1; j>0; --j)row[j] += row[j-1];vec.push_back(row);}return vec;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/pascals-triangle/description//// Author : liuyubobobo/// Time : 2018-06-03#include <iostream>#include <vector>using namespace std;/// Simulation (Dynamic Programming)/// Time Complexity: O(n^2)/// Space Complexity: O(1)class Solution {public:vector<vector<int>> generate(int numRows) {vector<vector<int>> res;if(numRows <= 0)return res;res.push_back({1});for(int i = 1 ; i < numRows ; i ++){vector<int> row;row.push_back(1);for(int j = 1 ; j < i ; j ++)row.push_back(res[i-1][j-1] + res[i-1][j]);row.push_back(1);res.push_back(row);}return res;}};int main() {return 0;}