forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExpression Add Operators.java
45 lines (45 loc) · 1.38 KB
/
Expression Add Operators.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
class Solution {
String s;
List<String>result;
int target;
public void operator(int i,int prev,long prod,long mid,String exp,List<Long>l){
if(i==l.size()){
if(mid+prod==target)
result.add(exp);
return;
}
if(prev==-1){
operator(i+1,0,-1*l.get(i)*l.get(i-1),mid+l.get(i-1),exp+"*"+l.get(i),l);
}else if(prev==1){
operator(i+1,0,l.get(i)*l.get(i-1),mid-l.get(i-1),exp+"*"+l.get(i),l);
}else{
operator(i+1,0,prod*l.get(i),mid,exp+"*"+l.get(i),l);
}
operator(i+1,-1,0,mid+prod-l.get(i),exp+"-"+l.get(i),l);
operator(i+1,1,0,mid+prod+l.get(i),exp+"+"+l.get(i),l);
}
public void rec(int in,List<Long>l){
if(in==s.length()){
operator(1,1,0,l.get(0),l.get(0)+"",l);
return;
}
if(s.charAt(in)=='0'){
l.add(0L);
rec(in+1,l);
l.remove(l.size()-1);
}else{
for(int i=in;i<s.length();i++){
l.add(Long.parseLong(s.substring(in,i+1)));
rec(i+1,l);
l.remove(l.size()-1);
}
}
}
public List<String> addOperators(String num, int target) {
result=new ArrayList<>();
this.s=num;
this.target=target;
rec(0,new ArrayList<>(30));
return result;
}
}