-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path241_diffWaysToAddParetheses.cpp
More file actions
91 lines (84 loc) · 2.31 KB
/
Copy path241_diffWaysToAddParetheses.cpp
File metadata and controls
91 lines (84 loc) · 2.31 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
82
83
84
85
86
87
88
89
90
91
#include <iostream>
#include <vector>
#include <algorithm>
#include <ctype.h>
using namespace std;
class Solution {
public:
size_t findOperator(string& input, int pos)
{
size_t plusPos = input.find('+', pos);
size_t multiPos = input.find('*', pos);
size_t minusPos = input.find('-', pos);
return min(min(plusPos, multiPos), minusPos);
}
vector<int> plus(vector<int>& left, vector<int>& right)
{
vector <int> res;
for (auto leftVal:left)
for (auto rightVal:right)
{
res.push_back(leftVal+rightVal);
}
return res;
}
vector<int> minus(vector<int>& left, vector<int>& right)
{
vector <int> res;
for (auto leftVal:left)
for (auto rightVal:right)
{
res.push_back(leftVal-rightVal);
}
return res;
}
vector<int> multi(vector<int>& left, vector<int>& right)
{
vector <int> res;
for (auto leftVal:left)
for (auto rightVal:right)
{
res.push_back(leftVal*rightVal);
}
return res;
}
vector<int> diffWaysToCompute(string input) {
vector<int> res;
int pos = findOperator(input, 0);
if (pos == -1)
{
res.push_back( stoi( input.c_str() ) );
return res;
}
while (pos != -1)
{
vector<int> left = diffWaysToCompute( input.substr(0, pos) );
vector<int> right = diffWaysToCompute( input.substr(pos+1, input.length()-pos-1) );
vector<int> newRes;
if (input[pos] == '+')
{
newRes = plus(left, right);
}
else if (input[pos] == '-')
{
newRes = minus(left, right);
} else if (input[pos] == '*')
{
newRes = multi(left, right);
} else {
cout << "Invalid input=" << input << endl;
}
pos = findOperator(input, ++pos);
res.insert( res.end(), newRes.begin(), newRes.end() );
}
return res;
}
};
int main()
{
Solution solution;
vector<int> res = solution.diffWaysToCompute("11");
for (auto val:res)
cout << val << ", ";
return 0;
}