C++ straight-forward backtracking solution


  • 1
    M
        bool flag=false;
        bool judgePoint24(vector<int>& nums) {
            vector<double> ns;
            for(int i=0;i<nums.size();i++) ns.push_back(nums[i]);
            BT(ns);
            return flag;
        }
        
        void BT(vector<double> ns) {
            if(flag) return;
            if(ns.size()==1&&abs(ns[0]-24.0)<0.001) flag=true;
            for(int i=0;i<ns.size();i++) {
                for(int j=0;j<ns.size();j++) {
                    if(i==j) continue;
                    vector<double> t=ns;
                    double a=t[i], b=t[j], p=min(i, j);
                    if(i<j) t.erase(t.begin()+j);
                    else t.erase(t.begin()+i);
                    t[p]=a+b;
                    BT(t);
                    t[p]=a-b;
                    BT(t);
                    t[p]=a*b;
                    BT(t);
                    if(b==0) continue;
                    t[p]=a/b;
                    BT(t);
                }
            }
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.