Leetcode 53.Maximum Subarray
题目描述
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]
代码
class Solution {
public:
vector<int> diffWaysToCompute(string input) {
vector<int> results, l, r;
int sSize = input.length();
char cur;
bool isAllInt = true;
for(int i = 0;i<sSize;i++){
cur = input[i];
//if cur char is an operator : '+', '-' or '*'
//get different ways computed values of left sub-string and right sub-string
//calculate possible results from l`Operate`r
if(cur=='-'||cur=='+'||cur=='*'){
isAllInt = false;
l = diffWaysToCompute(input.substr(0,i));
r = diffWaysToCompute(input.substr(i+1,sSize));
for(int i =0;i<l.size();i++)
for(int j=0;j<r.size();j++)
results.push_back(cur=='-'?l[i]-r[j]:cur=='+'?l[i]+r[j]:l[i]*r[j]);
}
}
//return the integer results
if(isAllInt){
results.push_back(atoi(input.c_str()));
}
return results;
}
};
算法描述
采用递归的方式进行计算
每个二元算式都是类似的基本形式
a Operate
b
对于双目运算符而言,可以通过获得左操作数数与右操作数,然后通过操作符进行操作
递归基:
对于输入字符串,如果没有操作符;则直接返回其结果
否则返回所有,左操作数o
右操作数的结果
递归步:
从左子字符串与右子字符串中获得可能的计算结果
复杂度分析:
不会-o-,应该与操作符个数及字符串长度相关