您的位置:首页 > Web前端

Different Ways to Add Parentheses

2016-07-15 19:09 204 查看
class Solution {
public:
vector<int> diffWaysToCompute(string input) {
vector<int> result;
int size = input.size();
for (int i = 0; i < size; i++) {
char cur = input[i];
if (cur == '+' || cur == '-' || cur == '*') {
// Split input string into two parts and solve them recursively
vector<int> result1 = diffWaysToCompute(input.substr(0, i));
vector<int> result2 = diffWaysToCompute(input.substr(i + 1));
for (auto n1 : result1) {//这两层循环为result变量添加值,供上一层迭代的result1和result2使用
for (auto n2 : result2) {
if (cur == '+')
result.push_back(n1 + n2);
else if (cur == '-')
result.push_back(n1 - n2);
else
result.push_back(n1 * n2);
}
}
}
}
// if the input string contains only number
if (result.empty())
result.push_back(atoi(input.c_str()));
return result;
}
};

以2*3-4*5为例子,整个迭代实现了如下5棵异构二叉树(按迭代先后顺序):









内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: