Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
24-game.py 1.98 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 2018-10-13 13:15 +08:00 . remove unused code
# Time: O(n^3 * 4^n) = O(1), n = 4
# Space: O(n^2) = O(1)
from operator import add, sub, mul, truediv
from fractions import Fraction
class Solution(object):
def judgePoint24(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(nums) == 1:
return abs(nums[0]-24) < 1e-6
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 nums[j] == 0):
continue
next_nums.append(op(nums[i], nums[j]))
if self.judgePoint24(next_nums):
return True
next_nums.pop()
return False
# Time: O(n^3 * 4^n) = O(1), n = 4
# Space: O(n^2) = O(1)
class Solution2(object):
def judgePoint24(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
def dfs(nums):
if len(nums) == 1:
return nums[0] == 24
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 nums[j] == 0):
continue
next_nums.append(op(nums[i], nums[j]))
if dfs(next_nums):
return True
next_nums.pop()
return False
return dfs(map(Fraction, nums))
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助