← Home

679. 24 Game

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
backtrackingC++Markdown
679

This is one of those problems where the clean idea matters more than the amount of code. For 679. 24 Game, the solution in this repository is mainly a backtracking solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: backtracking.

The notes already sitting in the source point us in the right direction:

  • DFS, need to consider epsilon!

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are dfs, judgePoint24, dnums.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//DFS, need to consider epsilon!
02//Runtime: 96 ms, faster than 20.53% of C++ online submissions for 24 Game.
03//Memory Usage: 18 MB, less than 12.62% of C++ online submissions for 24 Game.
04
05class Solution {
06public:
07    vector<char> ops;
08    
09    bool dfs(vector<double> nums){
10        int n = nums.size();
11        
12        // for(double& d : nums){
13        //     cout << d << " ";
14        // }
15        // cout << endl;
16        
17        if(n == 1){
18            /*
19            http://www.cplusplus.com/reference/cfloat/
20            DBL_EPSILON: 1e-9 or smaller
21            */
22            //69 / 70 test cases passed.
23            //fails [3,3,8,8] (expected true)
24            return abs(nums[0] - 24.0) < 1e-5;
25            // return abs(nums[0] - 24.0) < std::numeric_limits<double>::epsilon();
26        }else{
27            /*
28            choose any two elements and do operation,
29            so it's ok that we don't consider ()
30            */
31            for(int j = 1; j < n; ++j){
32                for(int i = 0; i < j; ++i){
33                    //choose two elements nums[i] and nums[j]
34					vector<double> nextnums = nums;
35                    //erase j and then i(j is larger)
36                    nextnums.erase(nextnums.begin()+j);
37                    nextnums.erase(nextnums.begin()+i);
38                    
39                    for(char& op : ops){
40                        if(op == '+'){
41                            nextnums.push_back(nums[i]+nums[j]);
42                        }else if(op == '-'){
43                            nextnums.push_back(nums[i]-nums[j]);
44                        }else if(op == '*'){
45                            nextnums.push_back(nums[i]*nums[j]);
46                        }else if(op == '/'){
47                            nextnums.push_back(nums[i]/nums[j]);
48                        }
49                        if(dfs(nextnums))
50                            return true;
51                        nextnums.pop_back();
52                    }
53                    
54                    /*
55                    forgetting this segment:
56                    66 / 70 test cases passed.
57                    [7,2,6,6]
58                    */
59                    for(char& op : ops){
60                        if(op == '+'){
61                            nextnums.push_back(nums[j]+nums[i]);
62                        }else if(op == '-'){
63                            nextnums.push_back(nums[j]-nums[i]);
64                        }else if(op == '*'){
65                            nextnums.push_back(nums[j]*nums[i]);
66                        }else if(op == '/'){
67                            nextnums.push_back(nums[j]/nums[i]);
68                        }
69                        if(dfs(nextnums))
70                            return true;
71                        nextnums.pop_back();
72                    }
73                }
74            }
75        }
76        
77        return false;
78    }
79    
80    bool judgePoint24(vector<int>& nums) {
81        ops = {'+', '-', '*', '/'};
82        
83        vector<double> dnums(nums.begin(), nums.end());
84        
85        return dfs(dnums);
86    }
87};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.