@@ -111,3 +111,42 @@ def fn(*args):
111
111
return False
112
112
113
113
return fn (* cards )
114
+
115
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
116
+ class Solution :
117
+ # All possible operations we can perform on two numbers.
118
+ def generate_possible_results (self , a : float , b : float ) - > List [float ]:
119
+ res = [a + b , a - b , b - a , a * b ]
120
+ if a :
121
+ res .append (b / a )
122
+ if b :
123
+ res .append (a / b )
124
+ return res
125
+
126
+ # Check if using current list we can react result 24.
127
+ def check_if_result_reached (self , cards : List [float ]) -> bool :
128
+ # Base Case: We have only one number left, check if it is approximately 24.
129
+ if len (cards ) == 1 :
130
+ return abs (cards [0 ] - 24.0 ) <= 0.1
131
+
132
+ for i in range (len (cards )):
133
+ for j in range (i + 1 , len (cards )):
134
+ # Create a new list with the remaining numbers and the new result.
135
+ new_list = [number for k , number in enumerate (cards ) if (k != i and k != j )]
136
+
137
+ # For any two numbers in our list, we perform every operation one by one.
138
+ for res in self .generate_possible_results (cards [i ], cards [j ]):
139
+ # Add the new result to the list.
140
+ new_list .append (res )
141
+
142
+ # Check if using this new list we can obtain the result 24.
143
+ if self .check_if_result_reached (new_list ):
144
+ return True
145
+
146
+ # Backtrack: remove the result from the list.
147
+ new_list .pop ()
148
+
149
+ return False
150
+
151
+ def judgePoint24 (self , cards : List [int ]) -> bool :
152
+ return self .check_if_result_reached (cards )
0 commit comments