【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 ...
随机推荐
- LearnPython_week3
函数说明 1 # -*- coding:utf-8 -*- 2 # Author:Wong Du 3 4 5 ###函数, 6 # 能避免代码重复, 7 # 方便代码修改等操作 8 def wong( ...
- Java 堆、栈、队列(遇见再更新)
目录 Java 栈.队列 栈 常用方法 案例 队列 Java 栈.队列 栈 常用方法 boolean empty() 测试堆栈是否为空 Object peek() 查看堆栈顶部的对象 Object p ...
- aboard, abolish
aboard board做动词有上车/船/飞机的意思,boarding就是正在上.board做名词有板的意思,车厢地板的板. a是个词根,有三种意思:1. 以某种状态或方式,如: ablaze, af ...
- 14. GLIBCXX_3.4.9' not found - 解决办法
在Linux中安装交叉编译器arm-linux-gcc 4.4.3,然后编译mini2440内核出错: /usr/lib/libstdc++.so.6: version GLIBCXX_3.4.9' ...
- Learning Spark中文版--第三章--RDD编程(2)
Common Transformations and Actions 本章中,我们浏览了Spark中大多数常见的transformation(转换)和action(开工).在包含特定数据类型的RD ...
- 3.7 rust 静态块
Cargo.toml [dependencies] lazy_static = "1.4.0" main.rs #[macro_use] extern crate lazy_sta ...
- jquery:iframe里面的元素怎样触发父窗口元素的事件?
例如父窗口定义了一个事件. top: $(dom1).bind('topEvent', function(){}); 那么iframe里面的元素怎样触发父窗口dom1的事件呢?这样吗? $(dom1, ...
- Spring Cloud简单项目创建
一.Zuul 原文链接 Zuul的主要功能是路由转发和过滤器.路由功能是微服务的一部分,比如/api/user转发到到user服务,/api/shop转发到到shop服务.zuul默认和Ribbon结 ...
- 【Word】自动化参考文献-交叉引用
第一步:设置参考文献标号 开始-定义新编号格式中,定义参考文献式的方框编号: 这里注意不要把他原来的数字去掉 第二步:选择交叉引用 插入-交叉引用: 第三步:更新标号 如果更新标号,使用右键-更新域. ...
- 12月第二周bug总结
1.bug总结 复制 别人的依赖和依赖指定类型 报错 解决:依赖还没加载完成,你就指定了版本型号,所以报错,所以先让他加载依赖,后指定该型号 eureka(优瑞卡) 注册服务 控制台没有显示出来的话 ...