#679

24 Game

expert · 1205 · lc hard +32 · verified · 59.4% accepted · 1,888 likes · top 57%

Description

Given a length-4 integer array cards where each value is in [1, 9], determine whether you can combine the four numbers using the operators ['+', '-', '*', '/'] and parentheses to produce exactly 24.

The following constraints apply:

- '/' denotes real division, not integer division (e.g., 4 / (1 - 2 / 3) = 12).

- Every operator is binary — '-' cannot be used as a unary negation.

- Numbers cannot be concatenated (e.g., 12 from cards [1, 2] is not allowed).

Return true if the value 24 is achievable, otherwise false.

Example 1:

Input: cards = [4,1,8,7]
Output: true
Explanation: (8-4) * (7-1) = 24

Example 2:

Input: cards = [1,2,1,2]
Output: false

Code

1
2
3