679. 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.
题目:每个数字都必须用到,且只能用一次。
1、DFS。
2、取出数组中两个数,然后相互加减乘除。
3、为了处理除法,所以用一个shu结构来存储分母分子。
class shu{
public:
int fenzi;
int fenmu;
shu(int x, int y = 1):fenzi(x), fenmu(y){}
};
class Solution {
public:
bool judgePoint24(vector<int>& nums)
{
vector<shu> num;
for (auto it : nums)
num.push_back(shu(it));
return helper(num);
}
bool helper(vector<shu>& nums) //成功返回1
{
if (nums.size() == 1 && nums[0].fenmu != 0 && nums[0].fenzi % nums[0].fenmu == 0 && nums[0].fenzi / nums[0].fenmu == 24)
return true;
int size = nums.size();
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
vector<shu> tmp_p = nums;
tmp_p.erase(tmp_p.begin() + i);
tmp_p.erase(tmp_p.begin() + j - 1);
tmp_p.push_back( shu(nums[i].fenzi*nums[j].fenmu + nums[i].fenmu * nums[j].fenzi, nums[i].fenmu * nums[j].fenmu));
if (helper(tmp_p)) return true;
vector<shu> tmp_j = nums;
tmp_j.erase(tmp_j.begin() + i);
tmp_j.erase(tmp_j.begin() + j - 1);
tmp_j.push_back( shu(abs(nums[i].fenzi * nums[j].fenmu - nums[i].fenmu * nums[j].fenzi), nums[i].fenmu * nums[j].fenmu));
if (helper(tmp_j)) return true;
vector<shu> tmp_c = nums;
tmp_c.erase(tmp_c.begin() + i);
tmp_c.erase(tmp_c.begin() + j - 1);
tmp_c.push_back( shu(nums[i].fenzi * nums[j].fenzi, nums[i].fenmu * nums[j].fenmu));
if (helper(tmp_c)) return true;
vector<shu> tmp_d1 = nums;
tmp_d1.erase(tmp_d1.begin() + i);
tmp_d1.erase(tmp_d1.begin() + j - 1);
tmp_d1.push_back( shu(nums[i].fenzi * nums[j].fenmu, nums[i].fenmu * nums[j].fenzi));
if (helper(tmp_d1)) return true;
vector<shu> tmp_d2 = nums;
tmp_d2.erase(tmp_d2.begin() + i);
tmp_d2.erase(tmp_d2.begin() + j - 1);
tmp_d2.push_back( shu(nums[i].fenmu * nums[j].fenzi, nums[i].fenzi * nums[j].fenmu));
if (helper(tmp_d2)) return true;
}
}
return false;
}
};