题解 | #24点运算# 参考霏坂的,就加了注释

24点运算

https://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d

a = input().split(' ')
card_dict = {'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8, '9': 9,'10': 10,'J': 11, 'Q': 12,'K': 13,'A': 1}

def dfs(card,target,out): # 入参:剩余的牌、剩余牌的值、拼接字符串
    if len(card)==1 and card_dict[card[0]]==target:
        L.append(card[0]+out)   # 最后一张牌拼接到out
    else:
        for i in range(len(wait)):      # 4张牌都会从最后面开始,分别进行+-*/递归。
            w = card[:i]+card[i+1::]    # 去掉序号 i 的牌
            c = card_dict[card[i]]      # 拿到 i 的牌
            dfs(w, target-c, '+'+wait[i]+out)
            dfs(w, target+c, '-'+wait[i]+out)
            dfs(w, target*c, '/'+wait[i]+out)
            dfs(w, target/c, '*'+wait[i]+out)

L = []
if 'joker' in a or 'JOKER' in a:
    print('ERROR')
else:
    dfs(a,24,'')
    if not L:
        print('NONE')
    else:
        print(L[0])

全部评论

相关推荐

点赞 评论 收藏
分享
07-20 21:57
已编辑
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务