Different Ways to Add Parentheses
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 *.
這道題主要思想是Divide and Conquer 分治法
對于一個表達式 a - b, a與b均為表達式,計算a - b的結果 我們需要先知道a的結果與b的結果。對于知道加parentheses的題,只要對表達中的每一個運算符都做這樣的操作并遞歸,就可以得出所有可能結果,希望下面的例子可以幫助理解
2 * 3 - 4 * 5
/ \
2 * (3 - 4 * 5) ...
/ \
(3 - 4 ) * 5 3 - (4 * 5)
/ \
3 4
class Solution {
public:
vector<int> diffWaysToCompute(string input) {
vector<int> result;
for (int i = 0; i < input.size(); i++) {
char c = input[i];
if (c == '+' || c == '-' || c == '*') {
auto result1 = diffWaysToCompute(input.substr(0, i));
auto result2 = diffWaysToCompute(input.substr(i + 1));
for (int r1: result1) {
for (int r2: result2) {
if (c == '+')
result.push_back(r1 + r2);
else if (c == '-')
result.push_back(r1 - r2);
else
result.push_back(r1 * r2);
}
}
}
}
if (result.empty())
result.push_back(atoi(input.c_str()));
return result;
}
};