# Leetcode:No.679 24 Game

You have 4 cards each containing a number from 1 to 9. You need to judge whether they could operated through *, /, +, -, (, ) to get the value of 24.
Example 1:
Input: [4, 1, 8, 7]
Output: True
Explanation: (8-4) * (7-1) = 24
Example 2:
Input: [1, 2, 1, 2]
Output: False
Note:

1. The division operator / represents real division, not integer division. For example, 4 / (1 - 2/3) = 12.
2. Every operation done is between two numbers. In particular, we cannot use - as a unary operator. For example, with [1, 1, 1, 1] as input, the expression -1 - 1 - 1 - 1 is not allowed.
3. You cannot concatenate numbers together. For example, if the input is [1, 2, 1, 2], we cannot write this as 12 + 12.

24点游戏，不过这里每个数都是1-9，并不是扑克牌。题目并没有直说4个都要用到，但是看例子是这个意思，实际上也是这个意思。

``````# Time:  O(n^3 * 4^n) = O(1), n = 4
# Space: O(n^2) = O(1)
from operator import add, sub, mul, truediv
class Solution(object):
def judgePoint24(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(nums) == 1:
return abs(nums[0]-24) <= 1e-3
ops = [add, sub, mul, truediv]
for i in xrange(len(nums)):
for j in xrange(len(nums)):
if i == j:
continue
next_nums = [nums[k] for k in xrange(len(nums)) if i != k != j]
for op in ops:
if ((op is add or op is mul) and j > i) or \
(op == truediv and abs(nums[j]) <= 1e-3):
continue
next_nums.append(op(nums[i], nums[j]))
if self.judgePoint24(next_nums):
return True
next_nums.pop()
return False
``````

### 推荐阅读更多精彩内容

• rljs by sennchi Timeline of History Part One The Cognitiv...
sennchi阅读 4,784评论 0 10
• Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
苏黎九歌阅读 9,416评论 0 39
• 路遥在《平凡的世界》里写道：我们宁愿去关心一个蹩脚演员的吃喝拉撒，也不愿意了解你身边任何一个朋友波澜壮阔的内心。这...
芳宝落落阅读 398评论 12 10
• “唧唧”“唧唧唧” 寂静的客厅突然听到几声清脆的鸟叫。咦，哪里来的这种声音，我可住的是城里20层的单元楼呀。 “唧...
武功茶舍阅读 33评论 0 4
• 在时代洪流中挣扎，fatigue、frustrated，swim forward,but still here. ...
Boryan阅读 208评论 0 0