[LeetCode] Different Ways to Add Parentheses
2015-08-17 11:20
363 查看
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
*.
Example 1
Input:
"2-1-1".
((2-1)-1) = 0 (2-(1-1)) = 2
Output:
[0, 2]
Example 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]
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
解题思路;
这道题可以用递归的方法来做。对于一个输入字符串s,一次获得每个标点符号的左侧left和右侧right的值,然后两两组合成结果。
class Solution {
public:
vector<int> diffWaysToCompute(string input) {
vector<int> result;
int len = input.length();
if(len == 0){
return result;
}
if(isInt(input)){
result.push_back(std::stoi(input));
return result;
}
for(int i=0; i<len; i++){
if(input[i]<'0' || input[i]>'9'){
vector<int> leftResult = diffWaysToCompute(input.substr(0, i));
vector<int> rightResult = diffWaysToCompute(input.substr(i+1));
for(int m = 0; m<leftResult.size(); m++){
for(int n = 0; n<rightResult.size(); n++){
switch(input[i]){
case '+':
result.push_back(leftResult[m] + rightResult
);
break;
case '-':
result.push_back(leftResult[m] - rightResult
);
break;
case '*':
result.push_back(leftResult[m] * rightResult
);
break;
}
}
}
}
}
return result;
}
bool isInt(string& s){
int len = s.length();
for(int i=0; i<len; i++){
if(s[i]<'0' || s[i]>'9'){
return false;
}
}
return true;
}
};
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- C++ Custom Control控件向父窗体发送对应的消息
- C++中拷贝构造函数的应用详解