作者: 负雪明烛
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. Demo04分解质因数

    package 习题集1;import java.util.Scanner;//将一个正整数分解质因数.例如输入90,打印出90=2*3*3*5public class Demo04 { public ...

  2. 03 Windows安装Java环境

    Java环境安装 使用微信扫码关注微信公众号,并回复:"Java环境",免费获取下载链接! 1.卸载(电脑未装此程序,跳过此过程)    找到电脑上面的控制面板    找到这两个文 ...

  3. Elasticsearch【基础入门】

    目录 一.操作index 1.查看index 2.增加index 3.删除index 二.操作index 1.新增document 2.查询type 全部数据 3.查找指定 id 的 document ...

  4. 商业爬虫学习笔记day1

    day1 一. HTTP 1.介绍: https://www.cnblogs.com/vamei/archive/2013/05/11/3069788.html http://blog.csdn.ne ...

  5. ORACLE CACHE BUFFER CHAINS原理

    原理图如下: 一个cache buffer chains 管理多个hash bucket,受隐含参数:_db_block_hash_buckets(控制管理几个hash bucket)

  6. html标签设置contenteditable时,去除粘贴文本自带样式

    在一个div标签里面加了可编辑的属性,从别的地方复制了一串文本,只想把文本内容存到接口里面,结果发现文本自带的标签和样式都会存进去. $(".session-new-name"). ...

  7. ssm中的注解

    1.@Controller 2.@RequestMapping 3.@RequestParam public String getUser(HttpSession session,@RequestPa ...

  8. Redis5.0.8 Cluster集群部署

    目录 一.Redis Cluster简介 二.部署 三.创建主库 一.Redis Cluster简介 Redis Cluster集群是一种去中心化的高可用服务,其内置的sentinel功能可以提供高可 ...

  9. InnoDB学习(四)之RedoLog和UndoLog

    BinLog是MySQL Server层的日志,所有的MySQL存储引擎都支持BinLog.BinLog可以支持主从复制和数据恢复,但是对事务的ACID特性支持比较差.InnoDB存储引擎引入Redo ...

  10. mit6.830-lab2-常见算子和 volcano 执行模型

    一.实验概览 github : https://github.com/CreatorsStack/CreatorDB 这个实验需要完成的内容有: 实现过滤.连接运算符,这些类都是继承与OpIterat ...