作者: 负雪明烛
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. centos yum安装mongodb,php扩展

    一,安装mongodb,php扩展 ? 1 [root@localhost ~]# yum install php-pecl-mongo mongodb mongodb-devel mongodb-s ...

  2. 零基础学习java------40---------Maven(maven的概念,安装,maven在eclipse中使用),springboot(spring整合springmvc(注解),spring整合mybatis(常见的配置文件)),前端页面(bootstrap软件)

    一 maven 1. Maven的相关概念 1.1 项目开发中遇到的问题 (1)都是同样的代码,为什么在我的机器上可以编译执行,而在他的机器上就不行? (2)为什么在我的机器上可以正常打包,而配置管理 ...

  3. go channel 概述

    精髓 将资源读进内存-->共享内存,一个个进程/线程进行处理,这是常见模式.go channel 是一种直接在进程/线程之间传递资源的方式,即以通信来共享内存.这便是go的精髓. 扩展-一些名词 ...

  4. velocity示例

    创建maven项目 pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns ...

  5. 最小化安装centos ubuntu基础命令

    # yum install vim iotop bc gcc gcc-c++ glibc glibc-devel pcre \ pcre-devel openssl openssl-devel zip ...

  6. 单元测试(Jest 和 Mocha)

    Vue CLI 拥有通过 Jest 或 Mocha 进行单元测试的内置选项. Jest 是功能最全的测试运行器.它所需的配置是最少的,默认安装了 JSDOM,内置断言且命令行的用户体验非常好.不过你需 ...

  7. git push大文件失败(write error: Broken pipe)完美解决

    问题 在使用git push推送大文件(超过了100MB)到GitHub远程仓库时提示异常,异常信息如下: fatal: sha1 file '<stdout>' write error: ...

  8. 11、Redis的配置文件

    Redis的配置文件 一.Redis配置文件简介 Redis是通过配置文件启动的 Redis对大小写字母不敏感 Redis基本上环境搭建都在配置文件 关于Redis配置文件位置是安装时放的位置,关于R ...

  9. Redis5.0.8 Cluster集群部署

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

  10. Log4j漏洞源码分析

    Log4j漏洞源码分析 这几天Log4j的问题消息满天飞,今天我们就一起来看看从源码角度看看这个漏洞是如何产生的. 大家都知道这次问题主要是由于Log4j中提供的jndi的功能. 具体涉及到的入口类是 ...