282. Expression Add Operators

class Solution {
public:
    vector<string> res;
    vector<string> addOperators(string num, int target) {
        if (num.length() == 0)  return res;
        helper(num, target, "", 0, 0, 0);
        return res;
    }
    void helper(const string& num, int target, string path, int pos, long val, long cur) {
        if (pos == num.length()) {
            if (target == val)
                res.push_back(path);
            return;
        }
        for (int len = 1; pos + len <= num.length(); len++) {
            if (len > 1 && num[pos] == '0') break;
            string cur_str = num.substr(pos, len);
            long cur_num = stol(cur_str);
            if (pos == 0)
                helper(num, target, cur_str, pos + len, cur_num, cur_num);
            else {
                helper(num, target, path + "+" + cur_str, pos + len, val + cur_num, cur_num);
                helper(num, target, path + "-" + cur_str, pos + len, val - cur_num, -cur_num);
                helper(num, target, path + "*" + cur_str, pos + len, val - cur + cur * cur_num, cur * cur_num);
            }
        }
    }
};

猜你喜欢

转载自www.cnblogs.com/JTechRoad/p/9072166.html