Leetcode 241. Different Ways to Add Parentheses
来源:互联网 发布:linux用cp复制文件 编辑:程序博客网 时间:2024/06/08 12:36
source url
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 Operate
b
对于双目运算符而言,可以通过获得左操作数数与右操作数,然后通过操作符进行操作
递归基:
对于输入字符串,如果没有操作符;则直接返回其结果
否则返回所有,左操作数o
右操作数的结果
递归步:
从左子字符串与右子字符串中获得可能的计算结果
复杂度分析:
不会-o-,应该与操作符个数及字符串长度相关
0 0
- [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
- 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
- [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
- 【LeetCode】241. Different Ways to Add Parentheses
- 【LeetCode】 241. Different Ways to Add Parentheses
- [LeetCode]241. Different Ways to Add Parentheses
- 新版Java为什么要修改substring的实现
- LocalBroadcast详解及源码分析
- 微信小程序版豆瓣同城
- tomcat 配置数据源
- 笛卡尔积
- Leetcode 241. Different Ways to Add Parentheses
- 取数字问题2-动规
- 【AngularJS】自定义过滤器
- 补充装饰器
- eee
- win10 安装 Python 和 pip工具
- PAT_A 1028. List Sorting (25)
- ScrollView 继续上拉查看图文详情
- 《机器学习实战》——Logistic回归