282. Expression Add Operators
2015-12-24 17:17
204 查看
Given a string that contains only digits
Examples:
0-9and 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 -> []
class Solution { public: vector<string> addOperators(string num, int target) { vector<string> res; if (num.size() == 0) return res; DFS(num, target, 0, "", res, 0, 0); return res; } void DFS(string& num, int& target, int cur, string path, vector<string>& res, long long diff, long long sum) { if (cur == int(num.size()) && sum == target) { res.push_back(path); return; } for (size_t i = cur; i < num.size(); i++) { string curStr = num.substr(cur, i - cur + 1); if (curStr.size() > 1 && curStr[0] == '0') return; long curVal = atol(curStr.c_str()); if (cur > 0) { DFS(num, target, i + 1, path + '+' + curStr, res, curVal, sum + curVal); DFS(num, target, i + 1, path + '-' + curStr, res, -curVal, sum - curVal); DFS(num, target, i + 1, path + '*' + curStr, res, diff * curVal, sum - diff + diff * curVal); } else { DFS(num, target, i + 1, path + curStr, res, curVal, sum + curVal); } } } };
相关文章推荐
- Android项目重构之路:架构篇
- devstack 部署openstack 开发环境
- Centos7编译安装MySQL5.5
- Linux每日学习(六)
- Hive UDAF和UDTF实现group by后获取top值
- Nginx之proxy_redirect详解
- MDK/Keil 中,J-Link调试查看变量值总是显示<not in scope>
- Linux每日学习(五)
- awk用法一
- 深入分析Docker镜像原理
- 使用mutt+msmtp做linux邮件客户端
- Linux ALSA声卡驱动之八:ASoC架构中的Platform
- C# 网站部署IIS常见异常及解决方法
- Linux ALSA声卡驱动之七:ASoC架构中的Codec
- Mac下tomcat配置ssl
- nginx基本配置与参数说明
- Linux ALSA声卡驱动之六:ASoC架构中的Machine
- Linux ALSA声卡驱动之五:移动设备中的ALSA(ASoC)
- 百万级PHP网站架构工具箱
- tomcat 默认web jndi配置