Python3 DFS 递归

24点游戏算法

http://www.nowcoder.com/questionTerminal/fbc417f314f745b1978fc751a54ac8cb

import sys
def dfs(nums):
    l = len(nums)
    if len(nums) == 1:
        return abs(nums[0] - 24) < eps
    for i in range(l):
        for j in range(i + 1, l):
            new_nums = [nums[k] for k in range(l) if i != k != j]
            if dfs(new_nums + [nums[i] + nums[j]]) or dfs(new_nums + [nums[i] - nums[j]]) or dfs(new_nums + [nums[j] - nums[i]])\
                    or dfs(new_nums + [nums[i] * nums[j]]) or (abs(nums[j]) > eps and dfs(new_nums + [nums[i] / nums[j]]))\
                    or (abs(nums[i]) > eps and dfs(new_nums + [nums[j] / nums[i]])):
                return True
    return False

eps = 1e-6
for line in sys.stdin:
    nums = list(map(int, line.split()))
    print('true' if dfs(nums) else 'false')
全部评论

相关推荐

10-09 22:05
666 C++
找到工作就狠狠玩CSGO:报联合国演讲,报电子烟设计与制造
点赞 评论 收藏
分享
6 4 评论
分享
牛客网
牛客企业服务