24 game [LeetCode 679]

来源:互联网 发布:js设置div背景图片 编辑:程序博客网 时间:2024/05/22 15:52

Description


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.

Analysis


一共有4个数 + 4个运算符

Step 1:随机挑选两个数(考虑顺序),共有12种情况
Step 2:为这两个排好序的数选择操作,共有4种情况,计算得出结果

现在只有3个数 + 4个运算符

Step 3:随机挑选两个数(考虑顺序),共有6种情况
Step 4:为这两个排好序的数选择操作,共有4种情况,计算得出结果

现在只剩下2个数 + 4个运算符

Step 5:这两个数排序,共有两种情况
Step 6:为这两个排好序的数选择操作,共有4种情况,计算得出结果

所以一共会有:1246424=9216种操作,因为这个数是固定的,所以时间复杂度为O(1),所以我选择使用简单粗暴的backtracking算法。

因为Step1,3,5都要考虑到数字的顺序,所以我决定使用一个可以输出数字全排列的函数next_permutation(nums.begin(), nums.end())(查资料)。使用这个函数,我们就不用考虑数字的排序了,只要考虑数字的组合和操作即可。

由于代码很简单,所以不做赘述。

Answer


#include <iostream>#include <algorithm>#include <vector>#include <cmath> //这个头文件可以使abs函数参数变为浮点数,也可直接使用fabs()using namespace std;class Solution {public:    bool judgePoint24(vector<int>& nums) {    //由于要输出全排序,要先将数字升序排好        sort(nums.begin(), nums.end());        do{        //注意一下下标必定从0开始不要犯这种错误            double a = nums[0], b = nums[1], c = nums[2], d = nums[3];            if (valid(a, b, c, d)) return true;        } while(next_permutation(nums.begin(), nums.end()));        return false;    }private:    bool valid(double a, double b, double c, double d) {    if (valid(a + b, c, d) || valid(a - b, c, d) || valid(a * b, c, d) || (b && valid(a / b, c, d))) return true;    if (valid(a, b + c, d) || valid(a, b - c, d) || valid(a, b * c, d) || (c && valid(a, b / c, d))) return true;    if (valid(a, b, c + d) || valid(a, b, c - d) || valid(a, b, c * d) || (d && valid(a, b, c / d))) return true;    return false;    }//要考虑到不能除0    bool valid(double a, double b, double c) {        if (valid(a + b, c) || valid(a - b, c) || valid(a * b, c) || (b && valid(a / b, c))) return true;        if (valid(a, b + c) || valid(a, b - c) || valid(a, b * c) || (c && valid(a, b / c))) return true;        return false;    }/*为什么是小于0.0001呢,因为double精度有限。有可能出现 2.0/3.0=0.666667,答案会有一点偏差*/    bool valid(double a, double b) {        if (abs(a + b - 24.0) < 0.0001 || abs(a - b - 24.0) < 0.0001 || abs(a * b - 24.0) < 0.0001 || (b && abs(a / b - 24.0) < 0.0001)) return true;        return false;    }};
原创粉丝点击