(nice!!!)(LeetCode 每日一题) 679. 24 点游戏 (深度优先搜索)
题目:679. 24 点游戏
思路:深度优先搜索dfs,时间复杂度0(n! * 6^n)。
从cards里选两个数,然后枚举所有情况,一共6种,继续dfs,直到cards数量为1。
C++版本:
class Solution {
public:const double wc=1e-9;bool dfs(vector<double> v){// 数量为1,判断该数是否为24if(v.size()==1){// 误差小于wc,说明是24return abs(v[0]-24)<wc;}int n=v.size();// 枚举cards里的两位数for(int i=0;i<n;i++){double x=v[i];for(int j=i+1;j<n;j++){double y=v[j];// 可能进行的操作vector<double> f={x+y,x-y,y-x,x*y};// 分母不为0if(x>wc){f.push_back(y/x);}if(y>wc){f.push_back(x/y);}auto new_v=v;new_v.erase(new_v.begin()+j);// 遍历可能进行的操作for(auto z:f){new_v[i]=z;if(dfs(new_v)){return true;}}}}return false;}bool judgePoint24(vector<int>& cards) {vector<double> v(cards.begin(),cards.end());return dfs(v);}
};