博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Different Ways to Add Parentheses
阅读量:7175 次
发布时间:2019-06-29

本文共 2016 字,大约阅读时间需要 6 分钟。

Well, this problem seems to be a little tricky at first glance. However, the idea (taken from ) is really simple. Let's take the equation 2*3-4*5 in the problem statement as an example to illustrate the idea. 

The idea is fairly simple: each time we encounter an operator, split the input string into two parts, one left to the operator and the other right to it. For example, when we reach -, we split the string into 2*3 and 4*5. Then we recursively (yeah, this is the biggest simplification) compute all possible values of the left and right parts and operate on all the possible pairs of them. The idea will become much more obvious if you read the following code.

1 class Solution { 2 public: 3     vector
diffWaysToCompute(string input) { 4 vector
outputs; 5 int n = input.length(); 6 for (int i = 0; i < n; i++) { 7 if (input[i] == '+' || input[i] == '-' || input[i] == '*') { 8 string left = input.substr(0, i); 9 string right = input.substr(i + 1, n - i - 1);10 vector
lval = diffWaysToCompute(left);11 vector
rval = diffWaysToCompute(right);12 for (int l : lval) {13 for (int r : rval) {14 switch (input[i]) {15 case '+':16 outputs.push_back(l + r);17 break;18 case '-':19 outputs.push_back(l - r);20 break;21 default:22 outputs.push_back(l * r);23 }24 }25 }26 }27 }28 if (outputs.empty())29 outputs.push_back(stoi(input));30 return outputs;31 }32 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4681579.html

你可能感兴趣的文章
使用Html和ashx文件实现其简单的注册页面
查看>>
ZeroMQ接口函数之 :zmq_inproc – ØMQ 本地进程内(线程间)传输方式
查看>>
C#语言基础原理及优缺点
查看>>
AIX系统开启ftp服务
查看>>
linux 上拷贝文件到windows 上 文件出现锁的文件
查看>>
Xamarin iOS教程之编辑界面编写代码
查看>>
Construct Binary Tree from Preorder and Inorder Traversal
查看>>
写得好 git 提交信息
查看>>
Linux下获取线程TID的方法
查看>>
Redis和Memcache的区别分析(转)
查看>>
网络请求 http get post 一
查看>>
《计算机问题求解》总结——2014年CCF计算机课程改革导教班(2014.07.11)
查看>>
Google Chrome Plus——绿色便携多功能谷歌浏览器
查看>>
Instant Run
查看>>
浏览器中 for in 反射 对象成员 的差异
查看>>
关于Linux启动时挂载rootfs的几种方式
查看>>
vs2015 系统找不到指定的文件(异常来自HRESULT:0x80070002)问题的解决方法
查看>>
2018年总结
查看>>
34个漂亮的应用程序后台管理界面
查看>>
java JDK6的可变参数
查看>>