282. Expression Add Operators

来源:互联网 发布:c 多进程编程 例子 编辑:程序博客网 时间:2024/06/05 06:31

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.

Examples: 

"123", 6 -> ["1+2+3", "1*2*3"] "232", 8 -> ["2*3+2", "2+3*2"]"105", 5 -> ["1*0+5","10-5"]"00", 0 -> ["0+0", "0-0", "0*0"]"3456237490", 9191 -> []

Credits:

Special thanks to @davidtan1890 for adding this problem and creating all test cases.


class Solution {public:    vector<string> addOperators(string num, int target) {        vector<string> res;        int n=num.size();        if(num.empty())return res;                for(int i=1;i<=n;i++){           long l=stol(num.substr(0,i));            //itol()            if(to_string(l).size()!=i)                continue;            dfs(res,num,target,i,num.substr(0,i),l,l,'#');        }        return res;    }private:        void dfs(std::vector<string>& res,string num,int target,int pos,string cur,const long pr,const long next,char op){        if(pos==num.size()&&target==pr){            res.push_back(cur);        }        else {            for(int i=pos+1;i<=num.size();i++){            long now=stol(num.substr(pos,i-pos));            if(to_string(now).size()==i-pos){                dfs(res,num,target,i,cur+'+'+num.substr(pos,i-pos),pr+now,now,'+');                dfs(res,num,target,i,cur+'-'+num.substr(pos,i-pos),pr-now,now,'-');                //dfs(res,num,target,i,cur+"*"+num.substr(pos,i-pos),op=='-'?(pr+next-next*now):((op=='+')?(pr-next+next*now):pr*now),pr*now,op);//报错,由于pr是前面所有的结果例如:a+b+c+d+e*f=pr,而next是紧挨着前面的值,例如:e*f,故而应该用next而不是pr                dfs(res,num,target,i,cur+"*"+num.substr(pos,i-pos),op=='-'?(pr+next-next*now):((op=='+')?(pr-next+next*now):next*now),next*now,op);                            }        }        }            }};