Skip to content

Commit 1e7bfd0

Browse files
committed
Add solution #679
1 parent 7ecb6ee commit 1e7bfd0

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -512,6 +512,7 @@
512512
676|[Implement Magic Dictionary](./0676-implement-magic-dictionary.js)|Medium|
513513
677|[Map Sum Pairs](./0677-map-sum-pairs.js)|Medium|
514514
678|[Valid Parenthesis String](./0678-valid-parenthesis-string.js)|Medium|
515+
679|[24 Game](./0679-24-game.js)|Hard|
515516
680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy|
516517
684|[Redundant Connection](./0684-redundant-connection.js)|Medium|
517518
686|[Repeated String Match](./0686-repeated-string-match.js)|Easy|

solutions/0679-24-game.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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

Comments
 (0)