Imagine you're a mathematician with four number cards in your hand, each showing a digit from 1 to 9. Your challenge? Combine these numbers using basic arithmetic operations (+, -, *, /) and parentheses to create an expression that equals exactly 24!
This is the classic 24 Game - a popular mathematical puzzle that tests your ability to think creatively with numbers. You have complete freedom to:
- ๐ Rearrange the numbers in any order
- ๐งฎ Use any combination of the four basic operations
- ๐ Group operations with parentheses however you like
Rules to remember:
- Division represents real division, not integer division (so 4 รท 3 = 1.333...)
- Every operation must be between two numbers - no unary minus allowed
- You cannot concatenate digits (no combining 1 and 2 to make 12)
- You must use all four cards exactly once
Return true if you can create a valid expression that equals 24, false otherwise.
Input & Output
Visualization
Time & Space Complexity
Although complex, it's constant time since we always have exactly 4 numbers - roughly O(4! * 4^3) = O(1536) operations
Recursion depth is at most 3 levels, and we use constant additional space
Constraints
- cards.length == 4
- 1 โค cards[i] โค 9
- Precision requirement: Consider two numbers equal if their difference is less than 10-6