-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathExpression Add Operators.cpp
More file actions
33 lines (33 loc) · 972 Bytes
/
Expression Add Operators.cpp
File metadata and controls
33 lines (33 loc) · 972 Bytes
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
class Solution {
public:
void f(int ind,string s,int target,vector<string> &ans,string tmp,long long prev,long long res){
if(ind==s.size()){
if(res==target)
ans.push_back(tmp);
return;
}
string st="";
long long curr=0;
for(int i=ind;i<s.size();i++){
if(i>ind && s[ind]=='0')
break;
st+=s[i];
curr=curr*10+s[i]-'0';
if(ind==0)
f(i+1,s,target,ans,tmp+st,curr,curr);
else{
f(i+1,s,target,ans,tmp+"+"+st,curr,res+curr);
f(i+1,s,target,ans,tmp+"-"+st,-curr,res-curr);
f(i+1,s,target,ans,tmp+"*"+st,prev*curr,res-prev+prev*curr);
}
}
return;
}
vector<string> addOperators(string s, int target) {
vector<string> ans;
string tmp="";
long long prev=0;
f(0,s,target,ans,tmp,prev,0);
return ans;
}
};