【LeetCode】241. Different Ways to Add Parentheses 解题报告(Python & C++)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/different-ways-to-add-parentheses/description/
题目描述
Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *.
Example 1
Input: "2-1-1".
((2-1)-1) = 0
(2-(1-1)) = 2
Output: [0, 2]
Example 2
Input: "2*3-4*5"
(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10
Output: [-34, -14, -10, -10, 10]
题目大意
给一个式子加上括号,看能够成的所有式子的值。
解题方法
方法一:递归构建所有表达式
这个题仍然可以使用回溯。通过dict保存有效的加括号方案,使用内置函数eval计算结果。
class Solution(object):
def diffWaysToCompute(self, input):
"""
:type input: str
:rtype: List[int]
"""
exprDict = dict()
nums, ops = [], []
input = re.split(r'(\D)', input)
for x in input:
if x.isdigit():
nums.append(x)
else:
ops.append(x)
self.dfs(nums, ops, exprDict)
return exprDict.values()
def dfs(self, nums, ops, exprDict):
if ops:
for x in range(len(ops)):
self.dfs(nums[:x] + ['(' + nums[x] + ops[x] + nums[x + 1] + ')'] + nums[x+2:], ops[:x] + ops[x+1:], exprDict)
elif nums[0] not in exprDict:
exprDict[nums[0]] = eval(nums[0])
方法二:分而治之
如果仔细想一想,能发现这个题和95. Unique Binary Search Trees II基本一模一样,都是分别求出左右的式子的值,然后再用循环拼接在一起。
方法是,循环遍历式子中的每个位置,如果这个位置是运算符,那么把左右的式子分别计算值,然后用运算符拼到一起。如果上面这个遍历中没有遇到运算符,那么res数组就是空的,这时input是个数字,所以结果把这个数字放进去,再返回即可。
Python代码如下:
class Solution(object):
def diffWaysToCompute(self, input):
"""
:type input: str
:rtype: List[int]
"""
res = list()
N = len(input)
for i in range(N):
if input[i] == "+" or input[i] == "-" or input[i] == "*":
lefts = self.diffWaysToCompute(input[:i])
rights = self.diffWaysToCompute(input[i+1:])
for left in lefts:
for right in rights:
if input[i] == "+":
res.append(left + right)
elif input[i] == "-":
res.append(left - right)
elif input[i] == "*":
res.append(left * right)
if not res:
res.append(int(input))
return res
C++代码如下:
class Solution {
public:
vector<int> diffWaysToCompute(string input) {
const int N = input.size();
vector<int> res;
for (int i = 0; i < N; ++i) {
if (input[i] == '+' || input[i] == '-' || input[i] == '*') {
vector<int> lefts = diffWaysToCompute(input.substr(0, i));
vector<int> rights = diffWaysToCompute(input.substr(i + 1));
for (int l : lefts) {
for (int r : rights) {
if (input[i] == '+')
res.push_back(l + r);
else if (input[i] == '-')
res.push_back(l - r);
else
res.push_back(l * r);
}
}
}
}
if (res.empty())
return {stoi(input)};
return res;
}
};
参考资料:
http://bookshadow.com/weblog/2015/07/27/leetcode-different-ways-add-parentheses/
http://www.cnblogs.com/grandyang/p/4682458.html
日期
2018 年 3 月 15 日 —— 雾霾消散,春光明媚
2018 年 11 月 15 日 —— 时间太快,不忍直视
2019 年 2 月 22 日 —— 这周结束了
【LeetCode】241. Different Ways to Add Parentheses 解题报告(Python & C++)的更多相关文章
- LN : leetcode 241 Different Ways to Add Parentheses
lc 241 Different Ways to Add Parentheses 241 Different Ways to Add Parentheses Given a string of num ...
- [LeetCode] 241. Different Ways to Add Parentheses 添加括号的不同方式
Given a string of numbers and operators, return all possible results from computing all the differen ...
- (medium)LeetCode 241.Different Ways to Add Parentheses
Given a string of numbers and operators, return all possible results from computing all the differen ...
- leetcode@ [241] Different Ways to Add Parentheses (Divide and Conquer)
https://leetcode.com/problems/different-ways-to-add-parentheses/ Given a string of numbers and opera ...
- [LeetCode#241]Different Ways to Add Parentheses
Problem: Given a string of numbers and operators, return all possible results from computing all the ...
- LeetCode 241. Different Ways to Add Parentheses为运算表达式设计优先级 (C++)
题目: Given a string of numbers and operators, return all possible results from computing all the diff ...
- leetcode 96. Unique Binary Search Trees 、95. Unique Binary Search Trees II 、241. Different Ways to Add Parentheses
96. Unique Binary Search Trees https://www.cnblogs.com/grandyang/p/4299608.html 3由dp[1]*dp[1].dp[0]* ...
- 241. Different Ways to Add Parentheses
241. Different Ways to Add Parentheses https://leetcode.com/problems/different-ways-to-add-parenthes ...
- 【LeetCode】241. Different Ways to Add Parentheses
Different Ways to Add Parentheses Given a string of numbers and operators, return all possible resul ...
随机推荐
- 修改unittest源码之tearDown
需求 最近在写selenium自动化平台,想把每条用例后面都带上截图,最开始是每条用例加上封装好的截图函数,但是发现太麻烦,就决定加在tearDown函数里面,每条用例结束后执行截图操作. 那么问题来 ...
- 脱离Editor、VS等IDE如何编译UE4工程
在Windows平台下,我们从.uproject文件生成VS解决方案.sln文件 .uproject文件用于打开Editor .sln文件用于打开VS工程 对于有增加C++代码的工程,Editor中和 ...
- 动态生成多个选择项【c#】
<asp:CheckBoxList ID="cbxLabelList" runat="server" RepeatColumns="10&quo ...
- C#时间选择
<script type="text/javascript" src="http://www.shicishu.com/down/WdatePicker.js&qu ...
- Z可读作zed的出处?
Commercial and international telephone and radiotelephone SPELLING ALPHABETS between World War I and ...
- Linux系统中安装软件方法总结
Linux系统中安装软件方法总结 [1]Linux系统中安装软件的几种方式 [2] Linux配置yum源(本地源和网络源) [3] SuSE下zypper源配置 [4] SUSE zypper 本地 ...
- Java实现单链表的增删查改及逆置打印
//所提供的接口 LinkList.java package Struct; public interface LinkList {//判断链表为空public boolean linkListIsE ...
- Linux学习 - 流程控制
一.if语句 1 单分支if条件语句 (1) if [ 条件判断式 ];then 程序 fi (2) if [ 条件判断式 ] then 程序 fi 例:检测根分区的使用量 2 双分支if条件语 ...
- Vue API 3 (模板语法 ,指令)
条件 v-if v-if 指令用于条件性地渲染一块内容.这块内容只会在指令的表达式返回 truthy 值的时候被渲染. v-show v-show 指令也是用于根据条件展示一块内容.v-show 只是 ...
- 用运oracel中的伪列rownum分页
在实际应用中我们经常碰到这样的问题,比如一张表比较大,我们只要其中的查看其中的前几条数据,或者对分页处理数据.在这些情况下我们都需要用到rownum.因此我们要理解rownum的原理和使用方法. Or ...