-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExpressionAddOperators.V2.js
More file actions
89 lines (80 loc) · 2.62 KB
/
ExpressionAddOperators.V2.js
File metadata and controls
89 lines (80 loc) · 2.62 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
// https://leetcode-cn.com/problems/expression-add-operators/
var Test = require('./Common/Test');
var addOperators = function (num, target) {
const operators = ['+', '-', '*', ''];
const result = [];
backTracing([], 0);
return result;
function backTracing(expr, index) {
// expr.push(num[index++]);
// index++;
// if (index == num.length) {
if (index == num.length - 1) {
expr.push(num[index]);
// const expr = expr.join('');
expr = expr.join('');
if (eval(expr) == target) {
result.push(expr);
}
}
else {
if (expr.length > 0) {
// expr = expr.slice();
const operator = expr[expr.length - 1];
// const operator = expr.pop();
// expr.push(num[index]);
switch (operator) {
case '+':
case '-':
const prevValue = eval(expr.join(''));
expr = [prevValue, operator];
// backTracing([prevValue, operator], index);
break;
case '*':
// backTracing([prevValue, operator], index);
break;
case '':
expr.pop();
expr[expr.length - 1] += num[index];
break;
}
}
else {
expr.push(num[index]);
}
for (const operator of operators) {
if (!(expr[expr.length - 1] == '0' && operator == '')) {
// switch (operator) {
// case '+':
// case '-':
// backTracing([prevValue, operator], index);
// break;
// case '*':
// // backTracing([prevValue, operator], index);
// break;
// case '':
// break;
// }
// expr.push(operator);
// backTracing([prevValue, operator], index);
// backTracing(expr, index + 1);
// expr.pop();
}
}
}
// expr.pop();
}
};
function test(num, target) {
Test.test(addOperators, num, target);
}
// test("123", 6);
// test("123", 15);
// test("232", 8)
// test("105", 5)
// test("00", 0)
// test("3456237490", 9191)
// "123"
// 6
// "123"
// 15