-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpascal_triangle2.cpp
92 lines (82 loc) · 1.74 KB
/
pascal_triangle2.cpp
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
82
83
84
85
86
87
88
89
90
91
92
// =====================================================================================
//
// Filename: pascal_triangle2.cpp
//
// Description:
//
// Version: 1.0
// Created: 08/16/2019 02:48:31 PM
// Revision: none
// Compiler: g++
//
// Author: Zhu Xianfeng (), [email protected]
// Organization:
//
// =====================================================================================
#include <stdio.h>
#include <stdlib.h>
#include <vector>
using std::vector;
// Non-recursive
class Solution1
{
public:
vector<int> getRow(int row_idx)
{
vector<int> nums(row_idx + 1, 0);
nums[0] = 1;
for (int i = 1; i < nums.size(); i++)
{
for (int j = i; j > 0; j--)
{
nums[j] = nums[j] + nums[j - 1];
}
}
return nums;
}
};
// Recursive
class Solution2
{
public:
vector<int> getRow(int row_idx)
{
vector<int> nums(row_idx + 1, 0);
generate(nums, row_idx);
return nums;
}
private:
void generate(vector<int>& nums, int row_idx)
{
if (row_idx == 0)
{
nums[0] = 1;
return;
}
generate(nums, row_idx - 1);
for (int i = row_idx; i >= 0; i--)
{
nums[i] = nums[i];
if (i > 0)
{
nums[i] += nums[i - 1];
}
}
}
};
using Solution = Solution2;
int main(int argc, char* argv[])
{
int row_idx = 3;
if (argc > 1)
{
row_idx = atoi(argv[1]);
}
auto nums = Solution().getRow(row_idx);
for (const auto& item: nums)
{
printf("%d ", item);
}
printf("\n");
return 0;
}