leetcode 679. 24 Game 4个数加减乘除得到24 + 24点游戏 + 暴力求解

淩亂°似流年 2022-06-03 08:25 233阅读 0赞

You have 4 cards each containing a number from 1 to 9. You need to judge whether they could operated through *, /, +, -, (, ) to get the value of 24.

Example 1:
Input: [4, 1, 8, 7]
Output: True
Explanation: (8-4) * (7-1) = 24
Example 2:
Input: [1, 2, 1, 2]
Output: False
Note:
The division operator / represents real division, not integer division. For example, 4 / (1 - 2/3) = 12.
Every operation done is between two numbers. In particular, we cannot use - as a unary operator. For example, with [1, 1, 1, 1] as input, the expression -1 - 1 - 1 - 1 is not allowed.
You cannot concatenate numbers together. For example, if the input is [1, 2, 1, 2], we cannot write this as 12 + 12.

本题题意很简单,最笨的方法就是直接考虑所有的情况

这道题值得反思,使用暴力求解还是不错的

需要注意的是最后两个数再多运算的时候设置了一个精度误差

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <set>
  5. #include <queue>
  6. #include <stack>
  7. #include <string>
  8. #include <climits>
  9. #include <algorithm>
  10. #include <sstream>
  11. #include <functional>
  12. #include <bitset>
  13. #include <numeric>
  14. #include <cmath>
  15. #include <regex>
  16. using namespace std;
  17. class Solution
  18. {
  19. public:
  20. bool judgePoint24(vector<int>& nums)
  21. {
  22. sort(nums.begin(), nums.end());
  23. do
  24. {
  25. if (valid(nums))
  26. return true;
  27. } while (next_permutation(nums.begin(), nums.end()));
  28. return false;
  29. }
  30. bool valid(vector<int>& nums)
  31. {
  32. double a = nums[0], b = nums[1], c = nums[2], d = nums[3];
  33. if (valid(a + b, c, d) || valid(a - b, c, d) || valid(a*b, c, d) || b != 0 && valid(a / b, c, d))
  34. return true;
  35. if (valid(a, b + c, d) || valid(a, b - c, d) || valid(a, b*c, d) || c != 0 && valid(a, b / c, d))
  36. return true;
  37. if (valid(a, b, c + d) || valid(a, b, c - d) || valid(a, b, c*d) || d != 0 && valid(a, b, c / d))
  38. return true;
  39. return false;
  40. }
  41. bool valid(double a, double b, double c)
  42. {
  43. if (valid(a + b, c) || valid(a - b, c) || valid(a*b, c) || b != 0 && valid(a / b, c))
  44. return true;
  45. if (valid(a, b + c) || valid(a, b - c) || valid(a, b*c) || c != 0 && valid(a, b / c))
  46. return true;
  47. return false;
  48. }
  49. bool valid(double a, double b)
  50. {
  51. if (abs(a + b - 24.0) < 0.0001 || abs(a - b - 24.0) < 0.0001
  52. || abs(a*b - 24.0) < 0.0001 || b!= 0 && abs(a / b - 24.0) < 0.0001)
  53. return true;
  54. return false;
  55. }
  56. };

发表评论

表情:
评论列表 (有 0 条评论,233人围观)

还没有评论,来说两句吧...

相关阅读

    相关 24游戏

    一.问题   随机生成4个代表扑克牌牌面的数字或字母,由用户输入包含这4个数字或字母的运算表达式(可包含括号),如果表达式计算结果为24就代表用户赢了此局

    相关 c++简单24游戏

    我的博客已经全部迁移到新地址,欢迎收藏我的[个人博客][Link 1]。 随机生成4个代表扑克牌牌面的数字字母,程序自动列出所有可能算出24的表达式,用擅长的语言(C/C++