[LeetCode] Expression Add Operators
2015-09-16 21:58
295 查看
This post shares a very nice solution, which is rewritten below.
class Solution { public: vector<string> addOperators(string num, int target) { int n = num.length(); if (!n) return {}; vector<string> ans; for (int i = 1; i <= n; i++) { string s = num.substr(0, i); long v = stol(s); if (s != to_string(v)) continue; add(ans, num, target, s, i, v, v, '$'); } return ans; } private: void add(vector<string>& ans, string& num, int target, string s, int i, long v, long pv, char op) { int n = num.length(); if (i == n && v == target) ans.push_back(s); else { for (int p = i + 1; p <= n; p++) { string t = num.substr(i, p - i); long d = stol(t); if (t != to_string(d)) continue; add(ans, num, target, s + '+' + t, p, v + d, d, '+'); add(ans, num, target, s + '-' + t, p, v - d, d, '-'); add(ans, num, target, s + '*' + t, p, (op == '+') ? v - pv + pv * d : ((op == '-') ? v + pv - pv * d: pv * d), pv * d, op); } } } };
相关文章推荐
- Linux上-DNS(bind)搭建2015091601
- 程序猿常用的好网站!
- windows下通过Runtime.getRuntime().exec.()执行linuxshell脚本
- CentOS7安装JDK
- Linux (Ubuntu/deepin等)终端命令安装Lamp
- sqlplus与shell互相传值的几种情况
- Linux java + apache mina + maven 实现高并发服务器
- OpenGL下的极坐标视图变换函数
- 嵌入式linux之SPI驱动
- docker私有仓库连接的问题
- Linux 权限
- windows下使用nginx(一)
- 消除linux中可执行文件的符号信息
- Linux汇编教程14:系统调用和文件处理下
- [LeetCode] Expression Add Operators 表达式增加操作符
- 虚拟机下linux连不上网
- Ubuntu14.04 下 OpenCV3 安装
- Photoshop的动作
- 开源单点登录框架CAS学习一 —— CAS的架构
- net-snmp5.7.3移植到arm-linux平台