leetcode 679. 24 點遊戲
阿新 • • 發佈:2022-03-02
1 class Solution { 2 public: 3 const double eps=1e-6; 4 int isok(vector<int>& cards) 5 { 6 vector<double>dp[4][4]; 7 for(int i=0;i<4;i++)dp[i][i].push_back((double)cards[i]); 8 for(int len=2;len<=4;len++) 9 for(int i=0;i+len-1<4;i++) 10 { 11 int j=i+len-1; 12 for(int k=i;k<j;k++) 13 { 14 int n1=dp[i][k].size(),n2=dp[k+1][j].size(); 15 for(int ii=0;ii<n1;ii++) 16 for(int jj=0;jj<n2;jj++) 17 { 18 19 dp[i][j].push_back(dp[i][k][ii]+dp[k+1][j][jj]); 20 dp[i][j].push_back(dp[i][k][ii]-dp[k+1][j][jj]); 21 dp[i][j].push_back(dp[i][k][ii]*dp[k+1][j][jj]); 22 if(dp[k+1][j][jj])dp[i][j].push_back(dp[i][k][ii]/dp[k+1][j][jj]); 23 } 24 } 25 } 26 for(auto &p:dp[0][3]) if(abs(p-24)<eps)return true; 27 return false; 28 } 29 bool judgePoint24(vector<int>& cards) { 30 sort(cards.begin(),cards.end()); 31 int n=24; 32 33 while(n) 34 { 35 if(isok(cards))return true; 36 next_permutation(cards.begin(),cards.end()); 37 n--; 38 } 39 return false; 40 } 41 };