题目如下:

解题思路:24点是非常经典的游戏了,因为本题数据量小,可以使用穷举法,把所有的可能结果都算出来。假设nums = [a,b,c,d],记f(n)表示用nums中n个数字进行运算可以得到的结果集,那么f(4)又可以记为f(4) = U(U(f(1),f(3), U(f(2),f(2))) (U表示合集),而f(3)又可以记为f(3) = U(f(1),f(2))。可知f(1)的结果集就是参数本身,f(2)的结果集是两个参数a,b进行四则运算的结果,最后判断24是否在结果集中即可。有一点要注意的是,除法运算会有浮点数产生,所以与24比较的时候要有一个浮动的区间。

代码如下:

class Solution(object):
def union(self,m,n):
r = []
for i in range(len(m)):
for j in range(len(n)):
r.append(m[i] + n[j])
r.append(m[i] - n[j])
r.append(m[i] * n[j])
if n[j] != 0:
r.append(float(m[i]) / float(n[j]))
if m[i] != 0:
r.append(float(n[j]) / float(m[i]))
return r def calc(self,l):
if len(l) == 1:
return l
elif len(l) == 2:
r = [l[0] + l[1],l[0] - l[1],l[0] * l[1],l[1] - l[0]]
if l[1] != 0:
r.append(float(l[0])/float(l[1]))
if l[0] != 0:
r.append(float(l[1])/float(l[0]))
return r
elif len(l) == 3:
return self.union(self.calc([l[0]]) , self.calc([l[1],l[2]])) + \
self.union(self.calc([l[1]]) , self.calc([l[0],l[2]])) + \
self.union(self.calc([l[2]]) , self.calc([l[0],l[1]])) def judgePoint24(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
r = [([nums[0]], [nums[1], nums[2], nums[3]]), ([nums[1]], [nums[0], nums[2], nums[3]]),
([nums[2]], [nums[0], nums[1], nums[3]]),
([nums[3]], [nums[0], nums[1], nums[2]]), ([nums[0], nums[1]], [nums[2], nums[3]]),
([nums[0], nums[2]], [nums[1], nums[3]]), ([nums[0], nums[3]], [nums[1], nums[2]])] for m,n in r:
m = self.calc(m)
n = self.calc(n)
result = self.union(m,n)
for res in result:
if abs(float(24) - float(res)) < 0.00000001:
return True
return False

最新文章

  1. 在VisualStadio2015上使用EF6.0建立MySql数据库
  2. 三、saltstack证书管理
  3. C函数及指针学习1
  4. openerp 常见问题 OpenERP在哪储存附件?(转载)
  5. [Everyday Mathematics]20150113
  6. 常见排序算法(JS版)
  7. 修改MYSQL最大连接数的2种方法
  8. Linux内核:sk_buff解析
  9. Windows Phone开发(32):路径之PathGeometry
  10. js选中文字兼容性解决
  11. nyoj1246 逃离妖洞 BFS
  12. webpack学习笔记——publicPath路径问题
  13. 译《The Part-Time Parliament》——终于读懂了Paxos协议!
  14. 【读书笔记】iOS-button只显示在一个界面的右下角,不管界面大小怎么变化(xib,没有使用自动布局)(一)
  15. mysql查询锁表语句
  16. Quart2D文字图像绘制
  17. USBDM Debugger interface for Freescale RS08,HCS08,HCS12,Coldfire and ARM-Kinetis Devices.
  18. 开始 App前 需要考虑的几项
  19. 局域网 ping
  20. 网络IO之阻塞、非阻塞、同步、异步总结【转】

热门文章

  1. boost Shared Memory
  2. php htmlspecialchars()函数 语法
  3. 【BZOJ3522&amp;BZOJ4543】Hotel加强版(长链剖分,树形DP)
  4. CSS布局浮动和定位属性的区别
  5. LintCode之奇偶分割数组
  6. AIZU 2560 [想法题]
  7. 114、TensorFlow设备放置
  8. Python 进阶_模块 & 包
  9. C#进阶系列——WebApi 路由机制剖析:你准备好了吗? 转载https://www.cnblogs.com/landeanfen/p/5501490.html
  10. Gentoo 搭遗