Techinpad: [LeetCode] Expression Add Operators
0-9 + , - 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
& 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 addOperators(string num, int target) { vector res;
Read full article from Techinpad: [LeetCode] Expression Add Operators
No comments:
Post a Comment