递归 | HJ67 24点游戏算法
# 最优解 import sys def func(nums, tar): if len(nums) == 1: return nums[0] == tar # 注意各种计算顺序都要考虑 for i in range(len(nums)): nums = nums[1:] + [nums[0]] if func(nums[1:], tar+nums[0]) or func(nums[1:], tar-nums[0]) \ or func(nums[1:], tar*nums[0]) or func(nums[1:], tar/nums[0]): return True return False for line in sys.stdin: nums = list(map(int, line.strip().split())) print(str(func(nums, 24)).lower()) # 我的代码 def func(left, nums, oprs): if not left: n1, n2, n3, n4 = nums[0], nums[1], nums[2], nums[3] opr1, opr2, opr3 = oprs[0], oprs[1], oprs[2] exp1 = eval(f'{n1}{opr1}{n2}') exp2 = eval(f'{exp1}{opr2}{n3}') exp3 = f'{exp2}{opr3}{n4}' if eval(exp3) == 24: res.append(exp3) return for i in range(len(left)): func(left[:i]+left[i+1:], nums+[left[i]], oprs+['+']) func(left[:i]+left[i+1:], nums+[left[i]], oprs+['-']) func(left[:i]+left[i+1:], nums+[left[i]], oprs+['*']) func(left[:i]+left[i+1:], nums+[left[i]], oprs+['/']) while True: try: n = list(map(int, input().split())) res = [] func(n, [], []) if res: print('true') else: print('false') except: break
用时:40min
华为笔试刷题 文章被收录于专栏
高质量题: 1~40:HJ16,HJ22,HJ24,HJ26,HJ27,HJ28,HJ35,HJ37,HJ39; 40~80:HJ41,HJ42,HJ43,HJ44,HJ48,HJ50,HJ52,HJ53,HJ57,HJ61,HJ63,HJ64,HJ70,HJ71,HJ74,HJ77; 80~108:HJ82,HJ85,HJ88,HJ89,HJ93,HJ95,HJ98,HJ103,HJ107