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); } } } }};
阅读全文
0 0
- 282. Expression Add Operators
- 282. Expression Add Operators
- 282. Expression Add Operators
- 282. Expression Add Operators
- 282. Expression Add Operators
- 282. Expression Add Operators
- 282. Expression Add Operators
- 282. Expression Add Operators
- 282. Expression Add Operators
- 282. Expression Add Operators
- 282. Expression Add Operators
- 282. Expression Add Operators
- 282. Expression Add Operators
- [leetcode] 282. Expression Add Operators
- [LeetCode]282. Expression Add Operators
- Leetcode 282. Expression Add Operators
- LeetCode 282. Expression Add Operators
- LeetCode 282. Expression Add Operators
- 数据结构实验:连通分量个数
- mysql:sql语句添加行号
- Mapper快速SQL生成
- Linux下使用Python的Tkinter库出现的No module named _tkinter问题
- Linux学习之路3
- 282. Expression Add Operators
- URL的组成
- 「翻译」Unity中的AssetBundle详解(一)
- ubuntu apt-get 出现NO_PUBKEY的解决方案
- 599. Minimum Index Sum of Two Lists
- 如何实现Google搜索(Windows10)
- CDN简述
- 校验日期正则表达式
- Canvas详解