题解 | #24点游戏算法#
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
应该是最完善的算法,就是加法乘法可能被计算次数多了一倍,懒得改了。
def dfs(): if len(cards) == 1: return abs(24 - cards[0]) < 0.0000001 for i in cards.copy(): cards.remove(i) for j in cards.copy(): cards.remove(j) cards.append(i + j) if dfs(): return True cards.pop() cards.append(i - j) if dfs(): return True cards.pop() cards.append(i * j) if dfs(): return True cards.pop() if j == 0: cards.append(j) continue cards.append(i / j) if dfs(): return True cards.pop() cards.append(j) cards.append(i) return False cards = list(map(int, input().split())) if dfs(): print('true') else: print('false')