题解 | #24点运算#
24点运算
https://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d
题目明确表示了从前往后依次运算,所以其实从后往前看,始终是(ABC)+/-/*//D的形式,所以dfs采用倒序遍历的方式,最末尾的数直接影响前面几个数应该的输出值,直接倒序打印遍历,即可找到对应的计算流程了
a = input().split(' ') dictory = {'J':11,'Q':12,'K':13,'A':1} def dfs(wait,target,out): if len(wait) == 1: if wait[0] in dictory: c = dictory[wait[0]] else: c = int(wait[0]) if target == c: L.append(wait[0]+out) else: for i in range(len(wait)): w = wait[:i]+wait[i+1::] if wait[i] in dictory: c = dictory[wait[i]] else: c = int(wait[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])