#679

24 Game

Hard
ArrayMathBacktrackingBacktrackingPermutations
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n!)
Space
O(1)
O(n)
💡

Intuition

Time O(n!)Space O(n)

We can use a backtracking approach to recursively try different combinations of numbers and operations, reducing unnecessary calculations by pruning paths that cannot lead to 24.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a recursive function that takes the current numbers and checks if we can reach 24.
  2. 2Step 2: For each pair of numbers, apply each operator and recursively call the function with the new number and the remaining numbers.
  3. 3Step 3: If at any point we reach 24, return true.
solution.py25 lines
1# Full working Python code
2from itertools import permutations
3
4def canGet24(cards):
5    def backtrack(nums):
6        if len(nums) == 1:
7            return abs(nums[0] - 24) < 1e-6
8        for i in range(len(nums)):
9            for j in range(len(nums)):
10                if i != j:
11                    next_nums = [nums[k] for k in range(len(nums)) if k != i and k != j]
12                    for op in ['+', '-', '*', '/']:
13                        if op == '+':
14                            next_nums.append(nums[i] + nums[j])
15                        elif op == '-':
16                            next_nums.append(nums[i] - nums[j])
17                        elif op == '*':
18                            next_nums.append(nums[i] * nums[j])
19                        elif nums[j] != 0:
20                            next_nums.append(nums[i] / nums[j])
21                        if backtrack(next_nums):
22                            return True
23        return False
24
25    return backtrack(cards)

Complexity note: The time complexity is O(n!) due to the permutations of numbers and combinations of operations, but we significantly reduce the number of evaluations through backtracking.

  • 1Understanding operator precedence is crucial.
  • 2Recognizing that not all combinations will yield valid results helps in pruning.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.