Problem
You are given an integer array cards
of length 4
. You have four cards, each containing a number in the range [1, 9]
. You should arrange the numbers on these cards in a mathematical expression using the operators ['+', '-', '*', '/']
and the parentheses '('
and ')'
to get the value 24.
You are restricted with the following rules:
- The division operator
'/'
represents real division, not integer division.- For example,
4 / (1 - 2 / 3) = 4 / (1 / 3) = 12
.
- For example,
- Every operation done is between two numbers. In particular, we cannot use
'-'
as a unary operator.- For example, if
cards = [1, 1, 1, 1]
, the expression"-1 - 1 - 1 - 1"
is not allowed.
- For example, if
- You cannot concatenate numbers together
- For example, if
cards = [1, 2, 1, 2]
, the expression"12 + 12"
is not valid.
- For example, if
Return true
if you can get such expression that evaluates to 24
, and false
otherwise.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
cards.length == 4
1 <= cards[i] <= 9
Method 1 – Backtracking
Intuition
Try all possible ways to combine the numbers with the four operators and parentheses, recursively, to check if 24 can be formed.
Approach
- Convert the input list to floats to handle division.
- If only one number remains, check if it is close enough to 24 (considering floating-point errors).
- For each pair of numbers, try all four operations (
+
,-
,*
,/
) in both possible orders (since subtraction and division are not commutative). - For each operation, create a new list with the result replacing the two numbers used, and recursively check if 24 can be formed.
- If any recursive call returns true, return true.
- If all possibilities are exhausted, return false.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(1)
(since the number of cards is fixed and small, all permutations and operations are bounded) - 🧺 Space complexity:
O(1)
(recursion depth and storage are bounded by the fixed input size)