24 Game — LeetCode 679 Python Solution
HardArrayMathBacktracking
- Problem
- #679
- Pattern
- Backtracking
- Reading time
- 5 min
- Source
- leetcode.com
The problem
You are given an integer array cards of length 4. You have four cards, each containing a number in the range [1, 9].
Example
- Input
- cards = [4,1,8,7]
- Output
- true
- Explanation
- (8-4) * (7-1) = 24
Python solution
Python
class Solution:
def judgePoint24(self, cards: List[int]) -> bool:
def dfs(nums: List[float]):
n = len(nums)
if n == 1:
if abs(nums[0] - 24) < 1e-6:
return True
return False
ok = False
for i in range(n):
for j in range(n):
if i != j:
nxt = [nums[k] for k in range(n) if k != i and k != j]
for op in ops:
match op:
case "/":
if nums[j] == 0:
continue
ok |= dfs(nxt + [nums[i] / nums[j]])
case "*":
ok |= dfs(nxt + [nums[i] * nums[j]])
case "+":
ok |= dfs(nxt + [nums[i] + nums[j]])
case "-":
ok |= dfs(nxt + [nums[i] - nums[j]])
if ok:
return True
return ok
ops = ("+", "-", "*", "/")
nums = [float(x) for x in cards]
return dfs(nums)Complexity
| Measure | Complexity |
|---|---|
| Time | Exponential (worst case) |
| Space | O(depth) auxiliary |
Pattern: Backtracking
Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 679. 24 Game is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.
The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 679. 24 Game?
- LeetCode 679. 24 Game is rated Hard on LeetCode.
- What topics does LeetCode 679. 24 Game cover?
- LeetCode 679. 24 Game is tagged Array, Math and Backtracking on LeetCode.