https://leetcode-cn.com/problems/24-game/
你有 4 张写有 1 到 9 数字的牌。你需要判断是否能通过 *,/,+,-,(,) 的运算得到 24。
示例 1:
输入: [4, 1, 8, 7]
输出: True
解释: (8-4) * (7-1) = 24
思路:遍历,技巧:使用函数指针
enum class Oper{
ADD,
SUB,
MUL,
DEV
};
#define EQUALV 0.00001
#define RET 24
double calc(double v1,Oper op,double v2){
switch(op){
case Oper::ADD:
return v1+v2;
case Oper::SUB:
return v1-v2;
case Oper::MUL:
return v1*v2;
case Oper::DEV:
if ( v2 != 0 ){
return v1/v2;
}
return 0xffffff;
}
return 0xffffff;
}
double func1(int v1,Oper op1,int v2, Oper op2, int v3,Oper op3, int v4){//(a b) c d
return calc(calc(calc(v1,op1,v2),op2,v3),op3,v4);
}
double func2(int v1,Oper op1,int v2, Oper op2, int v3,Oper op3, int v4){//(a b) (c d)
return calc(calc(v1,op1,v2),op2,calc(v3,op3,v4));
}
double func3(int v1,Oper op1,int v2, Oper op2, int v3,Oper op3, int v4){//a (b c) d
return calc(calc(v1,op1,calc(v2,op2,v3)),op3,v4);
}
double func4(int v1,Oper op1,int v2, Oper op2, int v3,Oper op3, int v4){//a ((b c) d)
return calc(v1,op1,calc(calc(v2,op2,v3),op3,v4));
}
double func5(int v1,Oper op1,int v2, Oper op2, int v3,Oper op3, int v4){//a (b (c d))
return calc(v1,op1,calc(v2,op2,calc(v3,op3,v4)));
}
class Solution {
public:
bool judgePoint24(vector& nums) {
static int index[]={0,1,2,3,0,1,3,2,0,2,1,3,0,2,3,1,0,3,1,2,0,3,2,1,
1,0,2,3,1,0,3,2,1,2,0,3,1,2,3,0,1,3,0,2,1,3,2,0,
2,0,1,3,2,0,3,1,2,1,0,3,2,1,3,0,2,3,0,1,2,3,1,0,
3,0,1,2,3,0,2,1,3,1,0,2,3,1,2,0,3,2,0,1,3,2,1,0};
double (*fp[5])(int a,Oper op1,int b,Oper op2,int c,Oper op3, int d);
fp[0] = func1;
fp[1] = func2;
fp[2] = func3;
fp[3] = func4;
fp[4] = func5;
for ( Oper i1=Oper::ADD; i1<=Oper::DEV; i1=(Oper)((int)i1+1 ))
for ( Oper i2=Oper::ADD; i2<=Oper::DEV; i2=(Oper)((int)i2+1 ))
for ( Oper i3=Oper::ADD; i3<=Oper::DEV; i3=(Oper)((int)i3+1 ))
for ( int i=0; i<5; ++i )
for ( int in=0; in<24; ++in ){
double ret = (fp[i])(nums[index[in*4]],i1,nums[index[in*4+1]],i2,nums[index[in*4+2]],i3,nums[index[in*4+3]]) ;
if ( fabs(RET-ret) < EQUALV ){
return true;
}
}
return false;
}
};