[LeetCode] 24 Game

679. 24 Game

You are given an integer array cards of length 4. You have four cards, each containing a number in the range [1, 9]. You should arrange the numbers on these cards in a mathematical expression using the operators [‘+’, ‘-‘, ‘*’, ‘/‘] and the parentheses ‘(‘ and ‘)’ to get the value 24.

You are restricted with the following rules:

  • The division operator ‘/‘ represents real division, not integer division.
  • For example, 4 / (1 - 2 / 3) = 4 / (1 / 3) = 12.
  • Every operation done is between two numbers. In particular, we cannot use ‘-‘ as a unary operator.
  • For example, if cards = [1, 1, 1, 1], the expression “-1 - 1 - 1 - 1” is not allowed.
  • You cannot concatenate numbers together
  • For example, if cards = [1, 2, 1, 2], the expression “12 + 12” is not valid.

Return true if you can get such expression that evaluates to 24, and false otherwise.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
bool op(double a, double b, double c, double d) {
if(op(a+b,c,d) || op(a-b,c,d) || op(a*b,c,d) || op(a/b,c,d)) return true;
if(op(a,b+c,d) || op(a,b-c,d) || op(a,b*c,d) || op(a,b/c,d)) return true;
if(op(a,b,c+d) || op(a,b,c-d) || op(a,b,c*d) || op(a,b,c/d)) return true;
return false;
}
bool op(double a, double b, double c) {
if(op(a+b,c) || op(a-b,c) || op(a*b,c) || b&&op(a/b,c)) return true;
if(op(a,b+c) || op(a,b-c) || op(a,b*c) || c&&op(a,b/c)) return true;
return false;
}
bool op(double a, double b) {
return judge(a + b) || judge(a - b) || judge(a * b) || b&&judge(a / b);
}
bool judge(double a) {
return abs(a - 24.0) < 0.1;
}
public:
bool judgePoint24(vector<int>& c) {
sort(c.begin(), c.end());
do {
if(op(c[0],c[1],c[2],c[3])) return true;
}while(next_permutation(begin(c), end(c)));

return false;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/29/PS/LeetCode/24-game/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.