Leetcode 241. Different Ways to Add Parentheses
2017-03-04 11:32
246 查看
source url
输入:一个算式,字符串形式
输出:该数组中,不同运算顺序的结果
如:
((2-1)-1) = 0
(2-(1-1)) = 2
每个二元算式都是类似的基本形式
a
对于双目运算符而言,可以通过获得左操作数数与右操作数,然后通过操作符进行操作
递归基:
对于输入字符串,如果没有操作符;则直接返回其结果
否则返回所有,左操作数
递归步:
从左子字符串与右子字符串中获得可能的计算结果
复杂度分析:
不会-o-,应该与操作符个数及字符串长度相关
Leetcode 53.Maximum Subarray
source url题目描述
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
Operateb
对于双目运算符而言,可以通过获得左操作数数与右操作数,然后通过操作符进行操作
递归基:
对于输入字符串,如果没有操作符;则直接返回其结果
否则返回所有,左操作数
o右操作数的结果
递归步:
从左子字符串与右子字符串中获得可能的计算结果
复杂度分析:
不会-o-,应该与操作符个数及字符串长度相关
相关文章推荐
- [leetcode] 241. Different Ways to Add Parentheses 解题报告
- 【LeetCode】 241. Different Ways to Add Parentheses
- leetCode刷题归纳-Divide and Conquer(241. Different Ways to Add Parentheses)
- LeetCode 241. Different Ways to Add Parentheses
- leetcode 241. Different Ways to Add Parentheses
- LeetCode 241. Different Ways to Add Parentheses
- 【leetcode题解】【再做一遍】【47】【M】241. Different Ways to Add Parentheses
- Leetcode 241. Different Ways to Add Parentheses
- leetcode 241. Different Ways to Add Parentheses
- 241. Different Ways to Add Parentheses LeetCode
- LeetCode *** 241. Different Ways to Add Parentheses
- [Leetcode] 241. Different Ways to Add Parentheses 解题报告
- [LeetCode]241. Different Ways to Add Parentheses
- [LeetCode]241. Different Ways to Add Parentheses
- LeetCode241. Different Ways to Add Parentheses
- LeetCode 241. Different Ways to Add Parentheses
- 【LeetCode】241. Different Ways to Add Parentheses
- <LeetCode OJ> 241. Different Ways to Add Parentheses
- [leetcode] 241. Different Ways to Add Parentheses
- leetcode 241. Different Ways to Add Parentheses-分治算法