Concise C++ DFS


  • 0
    G

    At each level, select two numbers and compute with + - * /, to get every possible answer.
    Note that - and / have order, need to compute a - b, b - a, a / b, b / a, four possible branches.

    class Solution {
    public:
        bool res = false;
        bool judgePoint24(vector<int>& nums) {
            vector<float> NUMS(nums.begin(), nums.end());
            return helper(NUMS);
        }
        bool helper(vector<float>& nums){
            if(nums.size() == 1){
                return abs(24 - nums[0]) < 0.00001;
            }
            for(int i = 0; i < nums.size(); i ++){
                for(int j = i+1; j < nums.size(); j ++){
                    vector<float> new_nums = nums;
                    float m = new_nums[i], n = new_nums[j];
                    new_nums.erase(new_nums.begin() + j);
                    
                    new_nums[i] = m + n; if(helper(new_nums)) return true;
                    new_nums[i] = m * n; if(helper(new_nums)) return true;
                    
                    new_nums[i] = m - n; if(helper(new_nums)) return true;
                    new_nums[i] = n - m; if(helper(new_nums)) return true;
                    
                    if(n != 0) {new_nums[i] = m / n; if(helper(new_nums)) return true;}
                    if(m != 0) {new_nums[i] = n / m; if(helper(new_nums)) return true;}
                }
            }
            return false;
        }
    };
    

Log in to reply
 

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