您的位置:首页 > 运维架构

leetcode282 : Expression Add Operators

2015-10-15 14:51 495 查看
1、原题如下:

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 -> []

2、解题如下:

class Solution {
public:
void dfs(vector<string>& result, const string num, const int target, int pos, string os, const long calres, const char lo, const long ln)
{
if (pos == num.size() && calres == target)
result.push_back(os);
else
{
for (int i = pos + 1; i <= num.size(); i++)
{
string nos = num.substr(pos, i - pos);
long nol = stol(nos);
if (to_string(nol).size() != i - pos) continue;
dfs(result, num, target, i, os + '+' + nos, calres + nol, '+', nol);
dfs(result, num, target, i, os + '-' + nos, calres - nol, '-', nol);
dfs(result, num, target, i, os + '*' + nos, (lo == '+') ? (calres - ln + ln*nol) : (lo == '-') ? (calres + ln - ln*nol) : ln*nol, lo, ln*nol);
}
}
}
//fos:first operational string
//fol:first operational long
//nos:next  operational string
//nol:next  operational long
//lo:last operator
//ln:last number
vector<string> addOperators(string num, int target) {
vector<string> result;
if (!num.size())  return result;
for (int i = 1; i <= num.size(); i++)
{
string fos = num.substr(0, i);//切割出第一个操作数
long fol = stol(fos);
if (to_string(fol).size() != i) continue;
dfs(result, num, target, i, fos, fol, ' ', fol);//(point1)

}
return result;
}
};


3、总结

这道题主要用的是dfs深度检索,遍历所有可能出现的情况。其实我们设想,如果num.size()为9,那就相当于有八个地方可以添加符号,我们可以选择填或者不填,虽然每两个数之间只能填一个操作符,但是总共填多少个并不限制,如此就会有很多种情况。point1之前首先确定第一个操作数,至于它到底有几位,我们根据循环来逐次遍历。然后启动dfs遍历功能,然后循环迭代,考虑下一个添加符号的位置在哪里(还是逐次遍历)操作完所有数之后就进行判断,看是否计算结果符合,符合就插入,不符合就继续之前的dfs~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode string c++ 面试