forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
expression-add-operators.cpp
64 lines (58 loc) · 2.16 KB
/
expression-add-operators.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
// Time: O(4^n)
// Space: O(n)
class Solution {
public:
vector<string> addOperators(string num, int target) {
vector<string> result;
vector<string> expr;
int val = 0;
string val_str;
for (int i = 0; i < num.length(); ++i) {
val = val * 10 + num[i] - '0';
val_str.push_back(num[i]);
// Avoid overflow and "00...".
if (to_string(val) != val_str) {
break;
}
expr.emplace_back(val_str);
addOperatorsDFS(num, target, i + 1, 0, val, &expr, &result);
expr.pop_back();
}
return result;
}
void addOperatorsDFS(const string& num, const int& target, const int& pos,
const int& operand1, const int& operand2,
vector<string> *expr, vector<string> *result) {
if (pos == num.length() && operand1 + operand2 == target) {
result->emplace_back(join(*expr));
} else {
int val = 0;
string val_str;
for (int i = pos; i < num.length(); ++i) {
val = val * 10 + num[i] - '0';
val_str.push_back(num[i]);
// Avoid overflow and "00...".
if (to_string(val) != val_str) {
break;
}
// Case '+':
expr->emplace_back("+" + val_str);
addOperatorsDFS(num, target, i + 1, operand1 + operand2, val, expr, result);
expr->pop_back();
// Case '-':
expr->emplace_back("-" + val_str);
addOperatorsDFS(num, target, i + 1, operand1 + operand2, -val, expr, result);
expr->pop_back();
// Case '*':
expr->emplace_back("*" + val_str);
addOperatorsDFS(num, target, i + 1, operand1, operand2 * val, expr, result);
expr->pop_back();
}
}
}
string join(const vector<string>& expr) {
ostringstream stream;
copy(expr.cbegin(), expr.cend(), ostream_iterator<string>(stream));
return stream.str();
}
};