-
Notifications
You must be signed in to change notification settings - Fork 0
/
expression_Add_Operator.java
59 lines (49 loc) · 1.59 KB
/
expression_Add_Operator.java
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
/*
Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value.
Example 1:
Input: num = "123", target = 6
Output: ["1+2+3", "1*2*3"]
Example 2:
Input: num = "232", target = 8
Output: ["2*3+2", "2+3*2"]
Example 3:
Input: num = "105", target = 5
Output: ["1*0+5","10-5"]
Example 4:
Input: num = "00", target = 0
Output: ["0+0", "0-0", "0*0"]
Example 5:
Input: num = "3456237490", target = 9191
Output: []
*/
class Solution {
//Backtracking
public List<String> addOperators(String num, int target) {
List<String> res = new ArrayList<>();
StringBuilder sb = new StringBuilder();
dfs(res, sb, num, 0, target, 0, 0);
return res;
}
public void dfs(List<String> res, StringBuilder sb, String num, int pos, int target, long prev, long multi) {
if(pos == num.length()) {
if(target == prev) res.add(sb.toString());
return;
}
for(int i = pos; i < num.length(); i++) {
if(num.charAt(pos) == '0' && i != pos) break;
long curr = Long.parseLong(num.substring(pos, i + 1));
int len = sb.length();
if(pos == 0) {
dfs(res, sb.append(curr), num, i + 1, target, curr, curr);
sb.setLength(len);
} else {
dfs(res, sb.append("+").append(curr), num, i + 1, target, prev + curr, curr);
sb.setLength(len);
dfs(res, sb.append("-").append(curr), num, i + 1, target, prev - curr, -curr);
sb.setLength(len);
dfs(res, sb.append("*").append(curr), num, i + 1, target, prev - multi + multi * curr, multi * curr);
sb.setLength(len);
}
}
}
}