1785. Card Target Game

Medium3.5 points estimatedBacktrackingMathsRecursion

In a party game each player is dealt a few number cards, stored in cards, and is challenged to reach the number target. A player must use every card exactly once, combining values with the four operations +, -, * and /, and may group the operations in any order, as if brackets were written anywhere. Either operand order is allowed for - and /.

Return true if some way of combining all the cards evaluates to exactly target, otherwise false. Division is exact rational division, never integer division, so 1 / 3 stays one third and later steps may multiply it back; dividing by zero is forbidden. Use backtracking: repeatedly pick two current values, replace them with each possible result, and recurse until one value remains, comparing exactly with fractions. Intended complexity: a small constant for at most 5 cards, using O(n) recursion depth.

Example 1

Input:
cards = [2,3,4], target = 10
Output:
true
Explanation:

Using every card, 2 * 3 + 4 = 10, so the target is reachable.

Example 2

Input:
cards = [1,1], target = 3
Output:
false
Explanation:

The only results from two cards of value 1 are 2, 0, 1 and 1, so 3 cannot be made.

Example 3

Input:
cards = [9,3,2], target = 9
Output:
true
Explanation:

Subtract 3 - 2 = 1, then multiply 9 * 1 = 9, which uses all three cards and hits the target.

Constraints

1 ≤ cards.length ≤ 5
1 ≤ cards[i] ≤ 13
-1000 ≤ target ≤ 1000

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O((n!)^2 * 4^(n-1)) worst case, n <= 5
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…