题目:

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)]

最新文章

  1. javascript数据结构与算法---检索算法
  2. jackson注解使用心得
  3. Thread-Safe Resource Manager
  4. Android中如何解决输入法键盘和activity页面遮挡的问题
  5. Java基础之写文件——将素数写入文件中(PrimesToFile)
  6. 每天一道LeetCode--409 .Longest Palindrome
  7. C++中Reference与指针(Pointer)的使用对比
  8. HDU 4287 Intelligent IME
  9. NSIS Installer(被NSI脚本编译出来的target)获取命令行参数
  10. SVG动画实践篇-模拟音量高低效果
  11. HelloGitHub.com 网站开源了
  12. http://codeforces.com/problemset/problem/712/D
  13. dubbox系列【四】——使用dubbo-monitor-x监控注册中心
  14. 【原创】大数据基础之Mesos+Marathon+Docker部署nginx
  15. 宏开发:excel中添加拼接行
  16. Linux shell判断文件和文件夹是否存在(转发)
  17. leetcode python 011
  18. Linux终端命令全面介绍
  19. SharePoint Framework 配置你的SharePoint客户端web部件开发环境
  20. Beyond Compare使用

热门文章

  1. (35)Spring Boot集成Redis实现缓存机制【从零开始学Spring Boot】
  2. Appendix B: Netsh Command Syntax for the Netsh Firewall Context
  3. 百度之星2014复赛 - 1001 - Find Numbers
  4. jquery-cookie持久化
  5. MySQL必知必会面试题 基础
  6. Windows 10家庭版也能共享打印机(中)解除Guest账户网络登录限制,实现局域网共享
  7. Shell编程中Shift的用法【转】
  8. 【撸码caffe 三】 caffe.cpp
  9. 第20章 Redis配置
  10. colab使用谷歌云中的文件