[leetcode]282. Expression Add Operators
来源:互联网 发布:动态数组clear函数 编辑:程序博客网 时间:2024/06/04 18:48
题目链接:https://leetcode.com/problems/expression-add-operators/description/
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 -> []
class Solution {private: // cur: {string} expression generated so far. // pos: {int} current visiting position of num. // cv: {long} cumulative value so far. // pv: {long} previous operand value. // op: {char} previous operator used. void dfs(std::vector<string>& res, const string& num, const int target, string cur, int pos, const long cv, const long pv, const char op) { if (pos == num.size() && cv == target) { res.push_back(cur); } else { for (int i=pos+1; i<=num.size(); i++) { string t = num.substr(pos, i-pos); long now = stol(t); if (to_string(now).size() != t.size()) continue; dfs(res, num, target, cur+'+'+t, i, cv+now, now, '+'); dfs(res, num, target, cur+'-'+t, i, cv-now, now, '-'); dfs(res, num, target, cur+'*'+t, i, (op == '-') ? cv+pv - pv*now : ((op == '+') ? cv-pv + pv*now : pv*now), pv*now, op); } } }public: vector<string> addOperators(string num, int target) { vector<string> res; if (num.empty()) return res; for (int i=1; i<=num.size(); i++) { string s = num.substr(0, i); long cur = stol(s); if (to_string(cur).size() != s.size()) continue; dfs(res, num, target, s, i, cur, cur, '#'); // no operator defined. } return res; }};
阅读全文
0 0
- [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
- 【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
- LeetCode:Expression Add Operators
- 【LeetCode】Expression Add Operators
- Expression Add Operators -- leetcode
- Leetcode -- Expression Add Operators
- LeetCode -- Expression Add Operators
- LeetCode Expression Add Operators
- leetcode:Expression Add Operators
- 《leetcode》:Expression Add Operators
- java主线程结束和子线程结束之间的关系
- dataTable处理
- MFC的文件操作 CFile 删除和重命名文件
- 工作5年后才明白的道理
- 页面js中文乱码怎么解决?
- [leetcode]282. Expression Add Operators
- C++进程注入
- 关于微信、QQ语音消息,语音电话的时候控制应用音频播放以及暂停
- Chromium 控件 DotNetBrowser V1.11发布 | 附下载
- Java IO里流的概念和转换流
- linux 常用工具
- Python命令行参数解析:getopt和argparse
- MVC @page 命令
- spark RDD分区2GB限制(Size exceeds Integer.MAX_VALUE)