Leetcode 241
来源:互联网 发布:光纤传输网络建设方案 编辑:程序博客网 时间:2024/04/27 22:05
题意
用字符串的形式给出一个由数字和+
,-
,*
给出的表达式,现在求表达式所有加入括号的情况的结果。
思路
分治法。
假设我们当前字符串的范围是[0, n - 1]。枚举一下操作符的位置k,即相当于(0, k - 1)加上括号,(k + 1, n - 1)加上括号。
我们统计一下(0, k - 1)
的所有计算结果为lh
,统计一下(k + 1, n - 1)
的所有结果为rh
。那么位置k上的所有结果为:
for (x in lh) for (y in rh) ans.push_back(x op y);
注意用vector
保存结果。
代码
class Solution {public: int cal(int x, int y, char op) { if (op == '+') return x + y; if (op == '-') return x - y; return x * y; } vector<int> diffWaysToCompute(string input) { int x = 0, i = 0; while (isdigit(input[i])) { x *= 10; x += input[i++] - '0'; } vector<int> ans; if (i == input.size()) {ans.push_back(x); return ans;} int n = input.size(); for (int i = 0; i < n; i++) { if (!isdigit(input[i])) { vector<int> lh = diffWaysToCompute(input.substr(0, i)); vector<int> rh = diffWaysToCompute(input.substr(i + 1, n - i - 1)); for (auto x : lh) { for (auto y : rh) { ans.push_back(cal(x, y, input[i])); } } } } return ans; }};
0 0
- Leetcode 241
- leetcode题库之241
- LeetCode 2016 282,241
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- 用快速傅里叶变换实现滤波
- 装饰设计模式简析
- java中组合的应用(不相干的类共同完成一个功能)+构造器回顾
- 小白程序媛的进击之路(Array)
- 1003: [ZJOI2006]物流运输
- Leetcode 241
- js获取浏览器滚动条宽度
- HDU2196Computer(树形DP)
- kafka设计解析-kafka Consumer设计解析
- 使用小米路由器设置ddns
- 多媒体视频播放器
- geotools 使用入门--配置与简单的一个例子
- bootstrap
- Zookeeper源码分析之序列化