代码拉取完成,页面将自动刷新
// Time: O(4^n)
// Space: O(n)
class Solution {
public:
vector<string> addOperators(string num, int target) {
vector<string> result;
vector<string> expr;
int val = 0;
string val_str;
for (int i = 0; i < num.length(); ++i) {
val = val * 10 + num[i] - '0';
val_str.push_back(num[i]);
// Avoid overflow and "00...".
if (to_string(val) != val_str) {
break;
}
expr.emplace_back(val_str);
addOperatorsDFS(num, target, i + 1, 0, val, &expr, &result);
expr.pop_back();
}
return result;
}
void addOperatorsDFS(const string& num, const int& target, const int& pos,
const int& operand1, const int& operand2,
vector<string> *expr, vector<string> *result) {
if (pos == num.length() && operand1 + operand2 == target) {
result->emplace_back(join(*expr));
} else {
int val = 0;
string val_str;
for (int i = pos; i < num.length(); ++i) {
val = val * 10 + num[i] - '0';
val_str.push_back(num[i]);
// Avoid overflow and "00...".
if (to_string(val) != val_str) {
break;
}
// Case '+':
expr->emplace_back("+" + val_str);
addOperatorsDFS(num, target, i + 1, operand1 + operand2, val, expr, result);
expr->pop_back();
// Case '-':
expr->emplace_back("-" + val_str);
addOperatorsDFS(num, target, i + 1, operand1 + operand2, -val, expr, result);
expr->pop_back();
// Case '*':
expr->emplace_back("*" + val_str);
addOperatorsDFS(num, target, i + 1, operand1, operand2 * val, expr, result);
expr->pop_back();
}
}
}
string join(const vector<string>& expr) {
ostringstream stream;
copy(expr.cbegin(), expr.cend(), ostream_iterator<string>(stream));
return stream.str();
}
};
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。