24点游戏
https://leetcode-cn.com/problems/24-game/submissions/
1. 因为是4张牌,4种运算,所以可以直接用枚举的方式。
2. 除法运算符 /
表示实数除法,而不是整数除法。例如 4 / (1 - 2/3) = 12 。所以可以设置一个epsilon = 1e-8,让计算的结果与24相减的绝对值与epsilon相比。
3. 将存放数字的list中挑选2个,4种运算枚举,list.remove挑选出的两个数字,list.append计算出的结果,直到list的长度为1。
4. 注意有可能出现除数为0的情况,得特殊处理。
class Solution:
eps = 1e-8
def cal(self, a, b, op):
if op == 0:
return a + b
elif op == 1:
return a - b
elif op == 2:
return a * b
elif op == 3:
return a / b
# 考虑real division 如何实现 (使用一个极小值,运算结果如果与24相减小于极小值)
def dfs(self, num):
if len(num) == 1:
return abs(num[0] - 24) < self.eps
for i in range(len(num)):
for j in range(len(num)):
if i != j:
for op in range(4):
if (op == 3) and (num[j] == 0):
pass
else:
res = self.cal(num[i], num[j], op)
temp_list = num.copy()
temp_list.remove(num[i])
temp_list.remove(num[j])
temp_list.append(res)
if self.dfs(temp_list):
return True
return False
def judgePoint24(self, nums: List[int]) -> bool:
"""
:type nums: List[int]
:rtype: bool
"""
return self.dfs(nums)