24 Game

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.

class Solution {
public:
    bool judgePoint24(vector<int>& nums) {
        deque<float> q;
        for(int x:nums)
        q.push_back(x);//使用deque,将所有元素压入deque中,准备进行处理
        return solve(q);
    }
    bool solve(deque<float> &q)
    {//递归枚举了所有的可能性
        const int len = q.size();
        if(len == 1)
        {
            return abs(q.front()-24)<eps;
        }
        for(int i=0;i<len;i++)
        {
            float a = q.front();
            q.pop_front();
            for(int j=1;j<len;j++)
            {
                float b =q.front();
                q.pop_front();
                if(search(q,a+b)||
                  search(q,a-b)||
                  search(q,a*b)||
                  (b?search(q,a/b):0)
                )
                return true;
                q.push_back(b);
            }
            q.push_back(a);
        }
        return false;
    }
    inline bool search(deque<float> &q,float v)
    {
        q.push_back(v);
        bool flag = solve(q);
        q.pop_back();
        return flag;
    }
private:
       float eps = 1e-5;//注意到浮点数运算的误差
};

注意:1.deque的用法 2.递归模拟出来所有运算的可能性,注意一次尝试结束后,需要将pop出的再压回去。

posted @ 2020-08-22 10:43  zmachine  阅读(133)  评论(0编辑  收藏  举报