-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathProblem2.java
More file actions
70 lines (66 loc) · 2.42 KB
/
Copy pathProblem2.java
File metadata and controls
70 lines (66 loc) · 2.42 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
// https://leetcode.com/problems/expression-add-operators/
// Time Complexity : O(4^n) where n is the length of the input string num.
// This is because for each digit, we have 4 choices: add an operator (+, -, *, or no operator).
// Space Complexity : O(n) where n is the length of the input string num.
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
class Solution {
public List<String> addOperators(String num, int target) {
List<String> result = new ArrayList<>();
helper(num, 0, 0l, 0l, new StringBuilder(), target, result);
return result;
}
private void helper(String num, int pivot, long calc, long tail, StringBuilder path, int target,
List<String> result) {
//base
if (pivot == num.length()) {
if (calc == target) {
result.add(path.toString());
}
return;
}
//logic
for (int i = pivot; i < num.length(); i++) {
long curr = Long.parseLong(num.substring(pivot, i + 1));
if (num.charAt(pivot) == '0' && pivot != i) {
continue;
}
int le = path.length();
if (pivot == 0) {
//top level
// 1 12 123
// action
path.append(curr);
// recurse
helper(num, i + 1, curr, curr, path, target, result);
// backtrack
path.setLength(le);
} else {
// +
// action
path.append("+");
path.append(curr);
// recurse
helper(num, i + 1, calc + curr, curr, path, target, result);
// backtrack
path.setLength(le);
// -
// action
path.append("-");
path.append(curr);
// recurse
helper(num, i + 1, calc - curr, -curr, path, target, result);
// backtrack
path.setLength(le);
// *
// action
path.append("*");
path.append(curr);
// recurse
helper(num, i + 1, calc - tail + tail * curr, tail * curr, path, target, result);
// backtrack
path.setLength(le);
}
}
}
}