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]
这道题是在表达式中添加括号改变运算优先级,计算所有情况的运算结果,题目难度为Medium。
首先需要从表达式中提取出数字和运算符,这一步比较简单就不再详述了,具体请看代码。依次在每个运算符位置将表达式分割成左右两部分,优先计算左右两部分所有可能的结果(相当于给左右两部分分别加了括号),然后再根据分割位置的运算符计算最终结果。这里通过分治法将问题分割成了左右两部分,通过递归计算左右两部分的结果即可组合出最终结果。如果表达式没有运算符,即只有一个数字的情况,直接返回该数字即可。具体代码:
class Solution {
void partation(const string& input, vector<int>& nums, vector<char>& ops) {
int num = 0;
for(char ch:input) {
if(ch == '+' || ch == '-' || ch == '*') {
ops.push_back(ch);
nums.push_back(num);
num = 0;
}
else {
num = num * 10 + ch - 0x30;
}
}
nums.push_back(num);
}
void compute(const vector<int>& nums, const vector<char>& ops, vector<int>& ret, int bgn, int end) {
for(int i = bgn; i <= end; ++i) {
vector<int> left, right;
if(i == bgn) left.push_back(nums[i]);
else compute(nums, ops, left, bgn, i-1);
if(i == end) right.push_back(nums[i+1]);
else compute(nums, ops, right, i+1, end);
for(int lRet:left) {
for(int rRet:right) {
if(ops[i] == '+') ret.push_back(lRet+rRet);
else if(ops[i] == '-') ret.push_back(lRet-rRet);
else ret.push_back(lRet*rRet);
}
}
}
}
public:
vector<int> diffWaysToCompute(string input) {
vector<int> nums, ret;
vector<char> ops;
partation(input, nums, ops);
if(ops.empty()) return nums;
compute(nums, ops, ret, 0, ops.size()-1);
return ret;
}
};
3万+




被折叠的 条评论
为什么被折叠?



