题解 | #24点游戏算法#

24点游戏算法

https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb



def dfs(nums):
    if len(nums) == 1:
        if abs(nums[0]-24) <= 1e-1:
            return True
        else:
            return False

    for i in range(len(nums)-1):
        for j in range(i+1, len(nums)):
            if i != j:
                a = nums[i]
                b = nums[j]
                ans = dfs(nums[:i] + nums[i+1:j] + nums[j+1:] + [a+b]) \
                or dfs(nums[:i] + nums[i+1:j] + nums[j+1:] + [a-b]) \
                or dfs(nums[:i] + nums[i+1:j] + nums[j+1:] + [a*b]) \
                or (b != 0 and dfs(nums[:i] + nums[i+1:j] + nums[j+1:] + [a/b]))
                if ans == True:
                    return ans
    return False

nums = list(map(int, input().split()))
if dfs(nums):
    print("true")
else:
    print("false")



全部评论

相关推荐

11-05 07:29
贵州大学 Java
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务