241. 为运算表达式设计优先级
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。
示例 1:
输入: "2-1-1"
输出: [0, 2]
解释:
((2-1)-1) = 0
(2-(1-1)) = 2
示例 2:
输入: "2*3-4*5"
输出: [-34, -14, -10, -10, 10]
解释:
(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10
思路
以运算符作为分点,两边再进行递归。没有碰到运算符的话就时那种输入的input为春数字的情况,这种情况发生在递归到最小一层时,或者原始输入就是纯数字的时候;如果res是空的话就确定是这种情况,则返回string转换的int。
stoi函数可以将 string转为 int。atoi()和 stoi()的区别—-数字字符串的处理
相同点:
①都是 C++的字符处理函数,把数字字符串转换成 int输出
②头文件都是#include
不同点:
①atoi()的参数是 const char* ,因此对于一个字符串 str我们必须调用 c_str()的方法把这个 string转换成 const char*类型的,而 stoi()的参数是 const string*,不需要转化为 const char*;
其中用到的substr函数:
substr的第一个参数为开始索引,第二个参数为长度 length;第二个 参数不写的话代表到达末尾。
substring的第一个参数也为开始索引,但第二个参数为结束索引。
class Solution {
public:
vector<int> diffWaysToCompute(string input) {
vector<int> res;
for(int i=0;i<input.size();i++){
char ch = input[i];
if(ch == '+' || ch == '-' || ch== '*'){
auto res1 = diffWaysToCompute(input.substr(0,i));
auto res2 = diffWaysToCompute(input.substr(i+1));
for(int k:res1){
for(int j:res2){
if(ch == '+')
res.push_back(k+j);
if(ch == '-')
res.push_back(k-j);
if(ch == '*')
res.push_back(k*j);
}
}
}
}
if(res.empty())
res.push_back(stoi(input));
return res;
}
};