标签:
Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +
, -
and *
.
Input: "2-1-1"
.
((2-1)-1) = 0 (2-(1-1)) = 2
Output: [0, 2]
Input: "2*3-4*5"
(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
Output: [-34, -14, -10, -10, 10]
class Solution {
public:
vector<int> diffWaysToCompute(string input) {
vector<int> result;
for(int i=0;i<input.size();i++){
char ch =input[i];
if(ch==‘+‘||ch==‘-‘||ch==‘*‘){
//递归对字符串0~i-1求计算的结果
vector<int> result1=diffWaysToCompute(input.substr(0,i));
//递归对字符串i+1~n-1求计算的结果
vector<int> result2=diffWaysToCompute(input.substr(i+1));
//对所有的结果,分别配对求与ch对应的计算结果,写入result之中
for(auto x:result1){
for(auto y:result2){
if(ch==‘+‘)
result.push_back(x+y);
else if(ch==‘-‘)
result.push_back(x-y);
else
result.push_back(x*y);
}
}
}
}
//如果result.size()==0,标明子串中只有数字,将其转换为数字,写入result之中
if(result.size()==0){
result.push_back(atoi(input.c_str()));
}
//返回result
return result;
}
};
class Solution {
private:
unordered_map<string,vector<int>> map;
public:
vector<int> diffWaysToCompute(string input) {
vector<int> result;
for(int i=0;i<input.size();i++){
char ch =input[i];
if(ch==‘+‘||ch==‘-‘||ch==‘*‘){
//递归对字符串0~i-1求计算的结果
vector<int> result1= map.find(input.substr(0,i))==map.end()? diffWaysToCompute(input.substr(0,i)):map[input.substr(0,i)];
//递归对字符串i+1~n-1求计算的结果
vector<int> result2= map.find(input.substr(i+1))==map.end()? diffWaysToCompute(input.substr(i+1)) :map[input.substr(i+1)];
//对所有的结果,分别配对求与ch对应的计算结果,写入result之中
for(auto x:result1){
for(auto y:result2){
if(ch==‘+‘)
result.push_back(x+y);
else if(ch==‘-‘)
result.push_back(x-y);
else
result.push_back(x*y);
}
}
}
}
//如果result.size()==0,标明子串中只有数字,将其转换为数字,写入result之中
if(result.size()==0){
result.push_back(atoi(input.c_str()));
}
map[input]=result;
//返回result
return result;
}
};
241.Different Ways to Add Parentheses
标签:
原文地址:http://www.cnblogs.com/zhoudayang/p/5008038.html