Clean C++ code with comments


  • 0
    S
    class Solution {
    public:
        vector<string> addOperators(string num, int target) {
            vector<string> res;
            bt(res, target, "", 0, 0, num);
            
            return res;
        }
        
        void bt(vector<string> &res, int target, string curString, long long curValue, long long diff, string leftString) {
            // If leftstring is empty and value is target
            if (leftString.size() == 0) {
                if (curValue == target) {
                    res.push_back(curString);
                }
            }
            
            for (int i = 0; i < leftString.size(); ++i) {
                // Get current string
                string cur = leftString.substr(0, i + 1);
                // Calculate current value
                long long val = stoll(cur.c_str());
                // Get left string
                string left = leftString.substr(i + 1);
                
                // Avoid 0*00, 0*05...
                if (cur.size() > 1 && cur[0] == '0') continue;
                if (curString.size() != 0) {
                    bt(res, target, curString + "+" + cur, curValue + val, val, left);
                    bt(res, target, curString + "-" + cur, curValue - val, -val, left);
                    bt(res, target, curString + "*" + cur, curValue - diff + diff * val, diff * val, left);
                } else {
                    bt(res, target, cur, val, val, left);
                }
            }
        }
    };
    

Log in to reply
 

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