题目:
Given a string that contains only digits 0-9
and a target value, return all possibilities to add binary operators (not unary) +
, -
, 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"] "105", 5 -> ["1*0+5","10-5"] "00", 0 -> ["0+0", "0-0", "0*0"] "3456237490", 9191 -> []
Credits:
Special thanks to @davidtan1890 for adding this problem and creating all test cases.
翻译:、
给定一个仅包含数字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 - > []
学分:
特别感谢@ davidtan1890添加此问题并创建所有测试用例。
解题代码:
class Solution {
private:
void f(vector<string> &strs, int target, string cur,string nums, long cv, long pv) {
if(nums.length() == 0) {
if(target == cv) strs.push_back(cur);
return ;
}
else {
for(int i = 1; i<= nums.length();i++) {
string num = nums.substr(0,i);
if(num.length() > 1 && num[0] == '0') return ;
// char* flag = NULL;
// char tem[i+1];
// strcpy(tem,num.c_str());
// cout << tem <<endl;
// long l = strtol(tem,&flag,10);
long l = stol(num);
// if(*flag != '\0') continue;
// cout << l<<endl;
string nextNums = nums.substr(i);
if(cur.length()!=0) {
f(strs,target,cur+'+'+num,nextNums,cv+l,l);
f(strs,target,cur+'-'+num,nextNums,cv-l,-l);
f(strs,target,cur+'*'+num,nextNums,cv-pv+pv*l,pv*l);
}
else {
f(strs,target,num,nextNums,l,l);
}
}
}
}
public:
vector<string> addOperators(string num, int target) {
vector<string> strs;
strs.clear();
if(num.empty()) return strs;
f(strs,target,"",num,0,0);
return strs;
}
};
解题状态:
class Solution {
private:
void f(vector<string> &strs, int target, string cur,string nums, long cv, long pv) {
if(nums.length() == 0) {
if(target == cv) strs.push_back(cur);
return ;
}
else {
for(int i = 1; i<= nums.length();i++) {
string num = nums.substr(0,i);
if(num.length() > 1 && num[0] == '0') return ;
// char* flag = NULL;
// char tem[i+1];
// strcpy(tem,num.c_str());
// cout << tem <<endl;
// long l = strtol(tem,&flag,10);
long l = stol(num);
// if(*flag != '\0') continue;
// cout << l<<endl;
string nextNums = nums.substr(i);
if(cur.length()!=0) {
f(strs,target,cur+'+'+num,nextNums,cv+l,l);
f(strs,target,cur+'-'+num,nextNums,cv-l,-l);
f(strs,target,cur+'*'+num,nextNums,cv-pv+pv*l,pv*l);
}
else {
f(strs,target,num,nextNums,l,l);
}
}
}
}
public:
vector<string> addOperators(string num, int target) {
vector<string> strs;
strs.clear();
if(num.empty()) return strs;
f(strs,target,"",num,0,0);
return strs;
}
};