-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPascal's_Triangle.cpp
More file actions
82 lines (68 loc) · 1.5 KB
/
Pascal's_Triangle.cpp
File metadata and controls
82 lines (68 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Source : https://oj.leetcode.com/problems/pascals-triangle/
// Author : zheng yi xiong
// Date : 2014-12-16
/**********************************************************************************
*
* 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]
* ]
*
**********************************************************************************/
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int> > generate(int numRows) {
if (0 == numRows)
{
vector<vector<int> > triangle;
return triangle;
}
vector<vector<int> > triangle(numRows);
triangle[0].push_back(1);
for (int i = 1; i < numRows; ++i)
{
triangle[i].push_back(1);
int j = 1;
for (; j <= i / 2; ++j)
{
triangle[i].push_back(triangle[i - 1][j - 1] + triangle[i - 1][j]);
}
for (; j <= i; ++j)
{
triangle[i].push_back(triangle[i][i - j]);
}
}
return triangle;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
int n = 8;
if ( argc > 1) {
n = _wtoi(argv[1]);
}
Solution so;
vector<vector<int> > pascal_triangle = so.generate(n);
cout<< "numRows = "<<n<<endl<<"triangle: [ \n";
for(int i= 0; i< n; ++i) {
cout<< " [ ";
for (int j = 0; j < i; ++j)
{
cout<<pascal_triangle[i][j]<< ", ";
}
cout<<pascal_triangle[i][i]<< " ]\n";
}
cout<<" ]\n";
system("pause");
return 0;
}