-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPascal's_Triangle_II.cpp
More file actions
73 lines (59 loc) · 1.37 KB
/
Pascal's_Triangle_II.cpp
File metadata and controls
73 lines (59 loc) · 1.37 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
// Source : https://oj.leetcode.com/problems/pascals-triangle-ii/
// Author : zheng yi xiong
// Date : 2014-12-16
/**********************************************************************************
*
* Given an index k, return the kth row of the Pascal's triangle.
* For example, given k = 3,
* Return [1,3,3,1].
* Note:
* Could you optimize your algorithm to use only O(k) extra space?
*
**********************************************************************************/
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> triangle_row(rowIndex + 1);
triangle_row[0] = 1;
if (0 == rowIndex)
{
return triangle_row;
}
for (int i = 1; i <= rowIndex; ++i)
{
triangle_row[1] = i;
int j = 2;
for (; j <= i / 2; ++j)
{
triangle_row[j] = triangle_row[i - j] + triangle_row[j];
}
for (; j <= i; ++j)
{
triangle_row[j] = triangle_row[i - j];
}
}
return triangle_row;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
int n = 6;
if ( argc > 1) {
n = _wtoi(argv[1]);
}
Solution so;
vector<int> pascal_row = so.getRow(n);
cout<< "numRows = "<<n<<endl<<"pascal row: [ \n";
cout<< " [ ";
for (int j = 0; j < n; ++j)
{
cout<<pascal_row[j]<< ", ";
}
cout<<pascal_row[n]<< " ]\n";
system("pause");
return 0;
}