679. 24 Game (Leetcode每日一题-2020.08.22)

Problem

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.

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.

Example1

Input: [4, 1, 8, 7]
Output: True
Explanation: (8-4) * (7-1) = 24

Example2

Input: [1, 2, 1, 2]
Output: False

Solution

暴力DFS。

class Solution {
public:
    bool judgePoint24(vector<int>& nums) {
        vector<double> d_nums;
        for(int i = 0;i<nums.size();++i)
            d_nums.push_back(nums[i]);
        return judgePoint24(d_nums);
        
    }

    bool judgePoint24(vector<double> &nums)
    {
        if(nums.empty())
            return false;
        if(nums.size() == 1)
            return abs(nums[0] - 24) < 1e-6;
        for(int i = 0;i<nums.size();++i)
        {
            for(int j = 0;j<nums.size();++j)
            {
                if(i != j)
                {
                    vector<double> new_nums;
                    for(int k = 0;k<nums.size();++k)
                    {
                        if(k != i && k != j)
                        {
                            new_nums.push_back(nums[k]);
                        }
                    }
                    
                    double sum = nums[i]+ nums[j];
                    new_nums.push_back(sum);
                    if(judgePoint24(new_nums))
                    {
                        return true;
                    }  
                    new_nums.pop_back();

                    double diff = nums[i] - nums[j];
                    new_nums.push_back(diff);
                    if(judgePoint24(new_nums))
                    {
                        return true;
                    }  
                    new_nums.pop_back();

                    double mul = nums[i] * nums[j];
                    new_nums.push_back(mul);
                    if(judgePoint24(new_nums))
                    {
                        return true;
                    }
                    new_nums.pop_back();

                    if(abs(nums[j] - 0) > 1e-6)
                    {
                        double div = nums[i] / nums[j];
                        new_nums.push_back(div);
                        if(judgePoint24(new_nums))
                        {
                            return true;
                        }
                        new_nums.pop_back();
                    }

                }
            }
        }

        return false;
    }
};

你可能感兴趣的:(letcode深度优先搜索)