C++ 中的表达式添加运算符
假设我们有一个字符串,其中只包含数字 0 到 9。并且给定一个目标值。我们必须返回所有可能的在数字中添加二元运算符 +、- 和 * 以获得目标值的方法。因此,如果输入类似于“232”且目标值为 8,则答案将为 [“2*3+2”, “2+3*2”]。
为了解决这个问题,我们将遵循以下步骤:
定义一个名为 solve() 的方法,它将接收索引、s、curr、target、temp、mult 作为参数。
如果 idx >= s 的大小,则:
如果 target 等于 curr,则:
将 temp 插入 ret 的末尾
返回
aux := 空字符串
初始化 i := idx,当 i < s 的大小,i 增加 1 时:
aux = aux + s[i]
如果 aux[0] 等于 '0' 且 aux 的大小 > 1,则:
跳到下一次迭代,忽略以下部分
如果 idx 等于 0,则:
调用 solve(i + 1, s, aux 作为整数, target, aux, aux 作为整数)
否则
调用 solve(i + 1, s, curr + aux 作为整数, target, temp + " + " + aux, aux 作为整数)
调用 solve(i + 1, s, curr - aux 作为整数, target, temp + " - " + aux, - aux 作为整数)
调用 solve(i + 1, s, curr - mult + mult * aux 作为整数, target, temp + " * " + aux, mult * aux 作为整数)
从主方法调用 solve(0, num, 0, target, 空字符串, 0)
返回 ret
示例
让我们看看以下实现,以便更好地理解:
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
typedef long long int lli;
class Solution {
public:
vector <string> ret;
void solve(int idx, string s, lli curr, lli target, string temp, lli mult){
//cout << temp << " " << curr << endl;
if(idx >= s.size()){
if(target == curr){
ret.push_back(temp);
}
return;
}
string aux = "";
for(int i = idx; i < s.size(); i++){
aux += s[i];
if(aux[0] == '0' && aux.size() > 1) continue;
if(idx == 0){
solve(i + 1, s, stol(aux), target, aux, stol(aux));
} else {
solve(i + 1, s, curr + stol(aux), target, temp + "+" + aux, stol(aux));
solve(i + 1, s, curr - stol(aux), target, temp + "-" + aux, -stol(aux));
solve(i + 1, s, curr - mult + mult * stol(aux), target, temp + "*" + aux, mult * stol(aux));
}
}
}
vector<string> addOperators(string num, int target) {
solve(0, num, 0, target, "", 0);
return ret;
}
};
main(){
Solution ob;
print_vector(ob.addOperators("232", 8));
}输入
"232", 8
输出
[2+3*2, 2*3+2, ]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP