给定一个仅包含数字 0 - 9 的字符串和一个目标值,返回在数字之间添加了 二元 运算符(不是一元)+, - 或 * 之后所有能得到目标值的情况。
样例:
"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []
#ifndef C653_H
#define C653_H
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Solution {
public:
/*
* @param num: a string contains only digits 0-9
* @param target: An integer
* @return: return all possibilities
*/
vector<string> addOperators(string &num, int target) {
// write your code here
vector<string> res;
if (num.empty())
return res;
vector<string> dic{ "+", "-", "*" };
string str;
helper(num, str, target, 0, 0, 0, res);
return res;
}
/* str表示添加了运算符的字符串,pos表示当前位置,
* curVal,preVal分别表示当前字符串运算的总和,上一步运算得到的值
* n表示当前的数字,当运算符是加号,当前字符串运算的总和就是之前的总和加上当前数字,将本次得到的数字值置为上一步运算得到的值
* 当运算符是乘号,需要减去上一步的值再加上上一步值与n的乘积
*/
void helper(string num, string str, int target, int pos, long long curVal, long long preVal, vector<string> &res)
{
if (pos == num.size()&&curVal==target)
{
res.push_back(str);
return;
}
for (int i = pos + 1; i <= num.size(); ++i)
{
string tmp = num.substr(pos,i-pos);
long long n = stoll(tmp);
if (tmp[0] == '0'&&tmp.size() > 1)
break;
if (pos == 0)
helper(num, tmp, target, i, n, n, res);
else
{
helper(num, str + "+" + tmp, target, i, curVal + n, n, res);
helper(num, str + "-" + tmp, target, i, curVal - n, -n, res);
helper(num, str + "*" + tmp, target, i, curVal - preVal + preVal*n, preVal*n, res);
}
}
}
};
#endif