算法8-----Different Ways to Add Parentheses(不同括号结果)
2024-08-29 02:05:55
题目:
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]
解法:分治法
思路:
分:遍历每个符号,分为符号前和后。如:"2-1-1-1",第1个‘-’分为 ‘2’ 和 ‘1-1-1’ ;第二个 '-' 分为 ‘2-1’ 和 ‘1-1’,第三个‘-’ 分为‘2-1-1’和‘1’
治:最后为一个数,则返回该数。
并:
对于每一次的分,如【2-1*3】 - 【1-1*4】 ,a=‘2-1*3’ 和 b=‘1-1*4’, a,b都递归计算所有的可能结果存入一个数组中,遍历相加减乘。a有2种结果【3,-1】,b有两种结果【0,-3】,如果a和b之间是 ‘-’,则 a-b 就会返回4种结果。
代码如下:
def diffWaysToCompute(input):
"""
:type input: str
:rtype: List[int]
"""
res=[]
result=0
for i,c in enumerate(input):
if c in "+-*":
for a in diffWaysToCompute(input[:i]):
for b in diffWaysToCompute(input[i+1:]):
if c=='+':
res.append(a+b)
elif c=='-':
res.append(a-b)
else:
res.append(a*b) return res or [int(input)]
最新文章
- javascript数据结构与算法---检索算法
- jackson注解使用心得
- Thread-Safe Resource Manager
- Android中如何解决输入法键盘和activity页面遮挡的问题
- Java基础之写文件——将素数写入文件中(PrimesToFile)
- 每天一道LeetCode--409 .Longest Palindrome
- C++中Reference与指针(Pointer)的使用对比
- HDU 4287 Intelligent IME
- NSIS Installer(被NSI脚本编译出来的target)获取命令行参数
- SVG动画实践篇-模拟音量高低效果
- HelloGitHub.com 网站开源了
- http://codeforces.com/problemset/problem/712/D
- dubbox系列【四】——使用dubbo-monitor-x监控注册中心
- 【原创】大数据基础之Mesos+Marathon+Docker部署nginx
- 宏开发:excel中添加拼接行
- Linux shell判断文件和文件夹是否存在(转发)
- leetcode python 011
- Linux终端命令全面介绍
- SharePoint Framework 配置你的SharePoint客户端web部件开发环境
- Beyond Compare使用
热门文章
- (35)Spring Boot集成Redis实现缓存机制【从零开始学Spring Boot】
- Appendix B: Netsh Command Syntax for the Netsh Firewall Context
- 百度之星2014复赛 - 1001 - Find Numbers
- jquery-cookie持久化
- MySQL必知必会面试题 基础
- Windows 10家庭版也能共享打印机(中)解除Guest账户网络登录限制,实现局域网共享
- Shell编程中Shift的用法【转】
- 【撸码caffe 三】 caffe.cpp
- 第20章 Redis配置
- colab使用谷歌云中的文件