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.Solution 1: Recursion.
vector<double> products(vector<int>& n, int L, int R) {
if(L == R) return {(double)n[L]};
vector<double> res;
for(int i=L; i<R; i++) {
vector<double> resl = products(n, L, i);
vector<double> resr = products(n, i+1, R);
for(auto l: resl) {
for(auto r: resr) {
res.push_back(l+r);
res.push_back(l-r);
res.push_back(l*r);
if(abs(r)>1e-8)
res.push_back(l/r);
}
}
}
return res;
}
bool judgePoint24(vector<int>& nums) {
sort(nums.begin(), nums.end());
do {
vector<double> res = products(nums, 0, nums.size()-1);
for(auto f: res) {
if(abs(f-24.0)<1e-6) return true;
}
} while(next_permutation(nums.begin(), nums.end()));
return false;
}
Solution 2.
double calc(double a, double b, int i, bool &s) {
switch(i) {
case 0: return a+b;
case 1: return a-b;
case 2: return a*b;
case 3: {
if(b==0) {
s = false;
return -1;
}
return a/b;
}
}
}
bool judge(int a, int b, int c, int d) {
bool s = true;
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++) {
for(int k=0; k<4; k++) {
s = true; // ((a,b),c),d
if(abs(calc(calc(calc(a,b,i,s),c,j,s),d,k,s) - 24.0)<0.01 && s) {
//cout<<a<<" "<<b<<" "<<c<<" "<<d<<endl;
//cout<<i<<" "<<j<<" "<<k<<" 01"<<endl;
return true;
}
s = true; // (a,(b,c)),d
if(abs(calc(calc(a, calc(b,c,j,s),i,s),d,k,s) - 24.0)<0.01 && s) {
//cout<<a<<" "<<b<<" "<<c<<" "<<d<<endl;
//cout<<i<<" "<<j<<" "<<k<<" 02"<<endl;
return true;
}
s = true; // (a,b),(c,d)
if(abs(calc(calc(a,b,i,s), calc(c,d,k,s),j,s) - 24.0)<0.01 && s) {
//cout<<a<<" "<<b<<" "<<c<<" "<<d<<endl;
//cout<<i<<" "<<j<<" "<<k<<" 03"<<endl;
return true;
}
s = true; // a,((b,c),d)
if(abs(calc(a,calc(calc(b,c,j,s),d,k,s),i,s) - 24.0)<0.01 && s) {
//cout<<a<<" "<<b<<" "<<c<<" "<<d<<endl;
//cout<<i<<" "<<j<<" "<<k<<" 04"<<endl;
return true;
}
s = true; // a,(b,(c,d))
if(abs(calc(a,calc(b,calc(c,d,k,s),j,s),i,s) - 24.0)<0.01 && s) {
//cout<<a<<" "<<b<<" "<<c<<" "<<d<<endl;
//cout<<i<<" "<<j<<" "<<k<<" 05"<<endl;
return true;
}
}
}
}
return false;
}
bool judgePoint24(vector<int>& nums) {
vector<int> idx = {0,1,2,3};
do {
int a = nums[idx[0]];
int b = nums[idx[1]];
int c = nums[idx[2]];
int d = nums[idx[3]];
if(judge(a,b,c,d)) return true;
} while(next_permutation(idx.begin(),idx.end()));
return false;
}
No comments:
Post a Comment