博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Different Ways to Add Parentheses
阅读量:7235 次
发布时间:2019-06-29

本文共 1633 字,大约阅读时间需要 5 分钟。

Different Ways to Add Parentheses

Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers andoperators. The valid operators are +, - and *.

Divide and Conquer

Time Complexity

O(Catalan数)
就是有多少种形态的树,时间复杂度就是多少
可以参考

思路

可以把这些方程想象是不同的二叉树,优先级越高的就在树的越底层,对于方程式,从左到右遍历一遍,一遇到运算符就提取出来作为根节点,数字一定是叶子节点。把树后序遍历一遍,先得到左右的值,再通过根节点的运算符计算一下。base case就是方程式中只剩下数字,没有运算符的时候,就可以开始返回了,这里用了一个boolean来标记这个string是不是数字。返回上来的左右list里的值,用了两个for loop把所以数字组合的可能性计算出来。

代码

public List
diffWaysToCompute(String input) { List
res = new ArrayList
(); boolean isNumber = true; //here we can remove base case, because we use for loop as the //base case, when input.length() == 0 means we reach the end for(int i = 0; i < input.length(); i++){ char c = input.charAt(i); if(c == '+' || c == '-' || c == '*'){ isNumber = false; List
left = diffWaysToCompute(input.substring(0, i)); List
right = diffWaysToCompute(input.substring(i + 1,input.length())); for (int x : left) { for (int y : right) { if (c == '-') { res.add(x - y); } else if (c == '+') { res.add(x + y); } else if (c == '*') { res.add(x * y); } } } } } if(isNumber) res.add(Integer.valueOf(input)); return res;}

优化

这题可能涉及大量的重复运算,所以可以把计算过的结果存储起来, 还没学会DP的存储,学会之后更新

转载地址:http://iagfm.baihongyu.com/

你可能感兴趣的文章
mongodb 中非常好用的 Aggregate
查看>>
C# ip地址和数字相互转换源码
查看>>
Mysql优化规范建议
查看>>
SPos共识机制:从去中心化到多中心思维改变
查看>>
集群和分布式区别
查看>>
Android Studio ADB Wifi 无线调试
查看>>
oppo9.0系统怎么不用ROOT激活XPOSED框架的教程
查看>>
MySQL----极客时间
查看>>
React Native for Android 环境配置
查看>>
聊聊Elasticsearch RestClient的NodeSelector
查看>>
编码、摘要和加密(二)——信息摘要
查看>>
Kotlin Android Extensions在Fragment中找不到控件的解决方法
查看>>
0322 - 响应 GitHub Webhooks 实现自动部署的 Web 服务
查看>>
命令行基础
查看>>
tensorflow生成tfrecord格式的数据
查看>>
Lamdba 表达式
查看>>
《Miss Talk》第02期:对话鲨鱼公园 赵文达
查看>>
Python 爬虫十六式 - 第八式:实例解析-全书网
查看>>
mpvue使用sass的解决方案
查看>>
横向滚动标题栏
查看>>