leetcode241
来源:互联网 发布:什么是数据票和进项票 编辑:程序博客网 时间:2024/06/05 16:23
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 *
.
(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
f分治题,以每个算数符为分界,分成左右两个部分,分别算出左右的解集,然后合并。
例如:
2*3-4*5
第一次*为分界限:2,3-4*5
2不能往下再分,3-4*5以每个运算符分界又可以分成 3,-,4*5 和 3-4,*,5 结果为-17和-5
所以[2], [-17,-5]组合变成[-34,-10]。
第二次以-分割:-14
第三次*分割:[-2,2] * [5] = -10,10
class Solution {
public:
int compute(char ch,int a,int b)
{
switch(ch)
{
case'+':return (a+b);
case'-':return (a-b);
case'*':return (a*b);
}
return 0;
}
vector<int> diffWaysToCompute(string input) {
vector<int> res;
bool flag =false; //代表有无运算符
for(int i=0;i<input.size();i++)
{
char ch = input[i];
if(ch=='+'||ch=='-'||ch=='*')
{
flag = true;
vector<int> left = diffWaysToCompute(input.substr(0,i));
vector<int> right = diffWaysToCompute(input.substr(i+1));
//左右区间合并
for(int j=0;j<left.size();j++)
{
for(int k=0;k<right.size();k++)
{
res.push_back(compute(ch,left[j],right[k]));
}
}
}
}
if(!flag) //没有运算符,只剩一个数的时候
{
stringstream ss(input);
int n;
ss>>n;
res.push_back(n);
}
return res;
}
};
- leetcode241
- Leetcode241: Valid Number
- leetcode241 java递归写法,重在思想
- leetcode241 : Different Ways to Add Parentheses
- LeetCode241. Different Ways to Add Parentheses
- LeetCode241——Different Ways to Add Parentheses
- 第二周:( LeetCode241 ) Different Ways to Add Parentheses(c++)
- DML,DDL,DCL的区别
- tcpdump
- Java JDK的安装与配置
- 论文共读 | “阳奉阴违”的半监督学习算法
- 基于SVM的分类识别 opencv3.1.0
- leetcode241
- CVE-2016-0199浅析-Internet Explorer内存损坏漏洞
- 第7章 Eclipse开发工具
- 前端自学之路---DOM
- Memcache课题研究
- 统计报表
- 3.基本bash shell命令
- Ubuntu命令终端查看使用过的命令
- c++中比较容易有歧义的语法