解题思路:深搜
遍历所有可能的情况,终止条件为表达式计算的结果等于target。注意,这里要使用long 类型保存整数,否则会溢出。我在vs2013,win32模式下使用long同样不能通过
"3456237490", 9191 -> []
这个案例,改用long long 才可以。
具体解析可以参考文末的这篇文章,讲的很好,主要要注意乘法情况下如何计算表达式的值。
class Solution { public: void compute(vector<string>& result, string exp, string num, long target, long cur_num, long pre_num) { if (cur_num == target&&num.size()==0) { result.push_back(exp); return; } for (int i = 1; i <= num.size(); i++) { string curStr = num.substr(0, i); if (curStr.size()>1 && curStr[0] == '0') return; long curTmp = stol(curStr); string nextStr = num.substr(i); if (exp.size() != 0) { compute(result,exp+"+"+curStr,nextStr,target,curTmp+cur_num,curTmp); compute(result,exp+"-"+curStr, nextStr, target, cur_num-curTmp, -curTmp); compute(result,exp+"*"+curStr, nextStr, target, (cur_num - pre_num) + pre_num*curTmp, pre_num*curTmp); } else{ compute(result, curStr, nextStr, target, curTmp, curTmp); } } } vector<string> addOperators(string num, int target) { vector<string> result; string exp = ""; long cur_num = 0; long pre_num = 0; compute(result, exp, num, target, cur_num, pre_num); return result; } };
参考:https://segmentfault.com/a/1190000003797204
时间: 2024-10-05 22:46:45