|
| 1 | +/** |
| 2 | + * 679. 24 Game |
| 3 | + * https://leetcode.com/problems/24-game/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an integer array cards of length 4. You have four cards, each containing a number |
| 7 | + * in the range [1, 9]. You should arrange the numbers on these cards in a mathematical expression |
| 8 | + * using the operators ['+', '-', '*', '/'] and the parentheses '(' and ')' to get the value 24. |
| 9 | + * |
| 10 | + * You are restricted with the following rules: |
| 11 | + * - The division operator '/' represents real division, not integer division. |
| 12 | + * - For example, 4 / (1 - 2 / 3) = 4 / (1 / 3) = 12. |
| 13 | + * - Every operation done is between two numbers. In particular, we cannot use '-' as a |
| 14 | + * unary operator. |
| 15 | + * - For example, if cards = [1, 1, 1, 1], the expression "-1 - 1 - 1 - 1" is not allowed. |
| 16 | + * - You cannot concatenate numbers together |
| 17 | + * - For example, if cards = [1, 2, 1, 2], the expression "12 + 12" is not valid. |
| 18 | + * |
| 19 | + * Return true if you can get such expression that evaluates to 24, and false otherwise. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number[]} cards |
| 24 | + * @return {boolean} |
| 25 | + */ |
| 26 | +const judgePoint24 = function(cards) { |
| 27 | + if (cards.length === 1) return Math.abs(cards[0] - 24) < 0.1; |
| 28 | + |
| 29 | + for (let i = 0; i < cards.length; i++) { |
| 30 | + for (let j = i + 1; j < cards.length; j++) { |
| 31 | + const remaining = new Array(cards.length - 1); |
| 32 | + for (let index = 0, current = 0; current < cards.length; current++) { |
| 33 | + if (i === current || j === current) continue; |
| 34 | + remaining[index++] = cards[current]; |
| 35 | + } |
| 36 | + const a = cards[i]; |
| 37 | + const b = cards[j]; |
| 38 | + const operations = [a + b, a - b, b - a, a * b, a / b, b / a]; |
| 39 | + for (const result of operations) { |
| 40 | + if (result === 0) continue; |
| 41 | + remaining[cards.length - 2] = result; |
| 42 | + if (judgePoint24(remaining)) return true; |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + return false; |
| 48 | +}; |
0 commit comments