282. Expression Add Operators
class Solution { public: vector<string> res; vector<string> addOperators(string num, int target) { if (num.length() == 0) return res; helper(num, target, "", 0, 0, 0); return res; } void helper(const string& num, int target, string path, int pos, long val, long cur) { if (pos == num.length()) { if (target == val) res.push_back(path); return; } for (int len = 1; pos + len <= num.length(); len++) { if (len > 1 && num[pos] == '0') break; string cur_str = num.substr(pos, len); long cur_num = stol(cur_str); if (pos == 0) helper(num, target, cur_str, pos + len, cur_num, cur_num); else { helper(num, target, path + "+" + cur_str, pos + len, val + cur_num, cur_num); helper(num, target, path + "-" + cur_str, pos + len, val - cur_num, -cur_num); helper(num, target, path + "*" + cur_str, pos + len, val - cur + cur * cur_num, cur * cur_num); } } } };
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步