作者: 负雪明烛
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++)的更多相关文章

  1. 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 ...

  2. [LeetCode] 241. Different Ways to Add Parentheses 添加括号的不同方式

    Given a string of numbers and operators, return all possible results from computing all the differen ...

  3. (medium)LeetCode 241.Different Ways to Add Parentheses

    Given a string of numbers and operators, return all possible results from computing all the differen ...

  4. 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 ...

  5. [LeetCode#241]Different Ways to Add Parentheses

    Problem: Given a string of numbers and operators, return all possible results from computing all the ...

  6. LeetCode 241. Different Ways to Add Parentheses为运算表达式设计优先级 (C++)

    题目: Given a string of numbers and operators, return all possible results from computing all the diff ...

  7. 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]* ...

  8. 241. Different Ways to Add Parentheses

    241. Different Ways to Add Parentheses https://leetcode.com/problems/different-ways-to-add-parenthes ...

  9. 【LeetCode】241. Different Ways to Add Parentheses

    Different Ways to Add Parentheses Given a string of numbers and operators, return all possible resul ...

随机推荐

  1. EXCEL ctrl+e 百变用法不只是你用的那么简单

    Excel2013版本中,新增加了一个快捷键:Ctrl+E,可以依据字符之间的关系,实现快速填充功能.一些需要使用公式或者其他功能进行解决的问题,现在只要一个快捷键就可以实现了. 用法1:快速拆解出需 ...

  2. nrf 51802 和 nrf51822 的区别于联系

    51802QFAA与51822QFAA在FLASH 跟RAM的容量没有差别:区别在于:a,接收灵敏度 51802是-91dBm;51822是-93dBm,这个差异导致接收距离有差异:b,Tx Powe ...

  3. REMI源安装php7.3

    参考:https://blog.csdn.net/Phplayers/article/details/100901352 php5.6安装参考:https://www.cnblogs.com/Easo ...

  4. 大数据学习----day27----hive02------1. 分桶表以及分桶抽样查询 2. 导出数据 3.Hive数据类型 4 逐行运算查询基本语法(group by用法,原理补充) 5.case when(练习题,多表关联)6 排序

    1. 分桶表以及分桶抽样查询 1.1 分桶表 对Hive(Inceptor)表分桶可以将表中记录按分桶键(某个字段对应的的值)的哈希值分散进多个文件中,这些小文件称为桶. 如要按照name属性分为3个 ...

  5. tomcat在eclipse上发布,Perference下的server找不到解决办法

    help--->Install New software得到如下所示 下面work with选项的内容与你的eclipse版本有关 我的eclipse版本为eclipse-java-2019-0 ...

  6. Swagger2异常 java.lang.NumberFormatException: For input string: ""

    问题在访问swagger首页时报错: java.lang.NumberFormatException: For input string: "" at java.lang.Numb ...

  7. keil 生成 bin 文件 gd32为例

    fromelf --bin --output .\update\GD32F4xZ.bin .\Output\GD32450Z_EVAL.axf代表使用的keil内的工具代表输出公式,..表示: 输出 ...

  8. Android 基础UI组件(二)

    1.Spinner 提供一个快速的方法来从一组值中选择一个值.在默认状态Spinner显示当前选择的值.触摸Spinner与所有其他可用值显示一个下拉菜单,可以选择一个新的值. /** * 写死内容: ...

  9. JAVA序列化浅析

    java.io.Serializable浅析 Java API中java.io.Serializable接口源码: 1 public interface Serializable { 2 } 类通过实 ...

  10. idea maven 项目 遇到 "Module not specified" 解决方法

    1. 原因:我这边出现的原因是 其他同事在提交代码是 将  这个文件夹也提交了,idea 会加载 .idea 里的配置(即 他的配置),而我的 maven 配置不同,导致出错. 2. 解决方法:删除这 ...