Wednesday, September 16, 2015

[LeetCode] Expression Add Operators

Given a string that contains only digits 0-9 and a target value, return all possibilities to add operators +-, or * between the digits so they evaluate to the target value.
Examples: 
"123", 6 -> ["1+2+3", "1*2*3"] 
"232", 8 -> ["2*3+2", "2+3*2"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []

class Solution {
void helper(vector<string>& res, string &nums, 
            string expr, long prev, 
            long curVal, int target) {
                
    if (nums.length() == 0 
        && curVal == target) {
        res.push_back(expr);
        return;
    }

    for (int i = 1; i<=nums.length(); i++) {
        
        string firstNum = nums.substr(0, i);
        
        if(i > 1 && firstNum[0] == '0') {
            return;
        }
        
        long first = stol(firstNum);
        string secondNum = nums.substr(i);

        if (expr.length() == 0) {
            helper(res, secondNum, firstNum, first, first, target);
            continue;
        }
        helper(res, secondNum, expr+"+"+firstNum, 
                first, curVal + first, target);
        helper(res, secondNum, expr+"-"+firstNum,
                -first, curVal - first, target);
        helper(res, secondNum, expr+"*"+firstNum, 
                prev*first, curVal-prev+prev*first, target);
    }
}

public:
    vector<string> addOperators(string num, int target) {
        vector<string> res;
        helper(res, num, "", 0, 0, target);
        return res;
    }
};