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

282. Expression Add Operators

2015-12-24 17:17 204 查看
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 -> []


class Solution {
public:
vector<string> addOperators(string num, int target) {

vector<string> res;
if (num.size() == 0)
return res;

DFS(num, target, 0, "", res, 0, 0);
return res;
}

void DFS(string& num, int& target, int cur, string path,
vector<string>& res, long long diff, long long sum) {

if (cur == int(num.size()) && sum == target) {
res.push_back(path);
return;
}
for (size_t i = cur; i < num.size(); i++) {
string curStr = num.substr(cur, i - cur + 1);
if (curStr.size() > 1 && curStr[0] == '0')
return;
long  curVal = atol(curStr.c_str());
if (cur > 0) {
DFS(num, target, i + 1, path + '+' + curStr, res, curVal,
sum + curVal);
DFS(num, target, i + 1, path + '-' + curStr, res, -curVal,
sum - curVal);
DFS(num, target, i + 1, path + '*' + curStr, res, diff * curVal,
sum - diff + diff * curVal);
} else {
DFS(num, target, i + 1, path + curStr, res, curVal,
sum + curVal);
}
}

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: