Different Ways to Add Parentheses
2016-07-15 19:09
204 查看
class Solution { public: vector<int> diffWaysToCompute(string input) { vector<int> result; int size = input.size(); for (int i = 0; i < size; i++) { char cur = input[i]; if (cur == '+' || cur == '-' || cur == '*') { // Split input string into two parts and solve them recursively vector<int> result1 = diffWaysToCompute(input.substr(0, i)); vector<int> result2 = diffWaysToCompute(input.substr(i + 1)); for (auto n1 : result1) {//这两层循环为result变量添加值,供上一层迭代的result1和result2使用 for (auto n2 : result2) { if (cur == '+') result.push_back(n1 + n2); else if (cur == '-') result.push_back(n1 - n2); else result.push_back(n1 * n2); } } } } // if the input string contains only number if (result.empty()) result.push_back(atoi(input.c_str())); return result; } };
以2*3-4*5为例子,整个迭代实现了如下5棵异构二叉树(按迭代先后顺序):
相关文章推荐
- jQuery on()方法
- input标签file类型,选择多个文件进行上传
- JSP
- css3样式
- web前端知识总结-BOM和DOM
- CSS3实现鼠标悬停动画
- JavaScript:立即执行的函数表达式
- IOS老工程pod适配ReactNative坑点
- html5 大文件断点上传
- [Effective JavaScript 笔记]第61条:不要阻塞I/O事件队列
- JavaScript实现拖拽预览,AJAX小文件上传
- css折叠样式(4)――div+css布局
- JavaScript实现拖拽预览,AJAX小文件上传
- jquery进度条实现 jquery-ul
- javascript实现图片隐写
- JavaScript八张思维导图概括
- Reactjs 'Symbol' is undefined in IE 11
- 【CSS】理解CSS
- html5与JavaScript脚本的六位彩票随机数字算法
- VS2015使用pjsip库编译一个helloworld工程