博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode——Submission Details
阅读量:7048 次
发布时间:2019-06-28

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

Description:

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 *.

Example 1

Input: "2-1-1".

((2-1)-1) = 0(2-(1-1)) = 2

Output: [0, 2]

Example 2

Input: "2*3-4*5"

(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

Output: [-34, -14, -10, -10, 10]

Credits:

Special thanks to  for adding this problem and creating all test cases.

使用分治递归的方法首先将问题划分成子问题,再对子问题的解进行全排列合并,最终得到问题的解。

深刻理解递归还是很有必要的。

public class Solution {    public List
diffWaysToCompute(String input) { List
resList = new ArrayList
(); for(int i=0; i
leftList = diffWaysToCompute(input.substring(0, i)); List
rightList = diffWaysToCompute(input.substring(i+1)); for(int left : leftList) { for(int right : rightList) { if(op == '+') { resList.add(left + right); } else if(op == '-') { resList.add(left - right); } else { resList.add(left * right); } } } } } if(resList.size() == 0) { resList.add(Integer.parseInt(input)); } return resList; }}

这题竟然没有不是个位数的case。

转载于:https://www.cnblogs.com/wxisme/p/4850813.html

你可能感兴趣的文章
专访ThoughtWorks王磊:从单块架构到微服务架构
查看>>
JetBrains大力推广Kotlin为哪般?
查看>>
IBM首家发布了公有云中的裸机Kubernetes
查看>>
CA发布其工作负载自动化引擎的新版本
查看>>
火掌柜iOS端基于CocoaPods的组件二进制化实践
查看>>
微软发起Java on Azure调查,呼吁Java社区积极参与
查看>>
Zabbix Agent端配置文件说明
查看>>
2.10环境变量PATH;2.11cp命令;2.12mv命令;2.13文档查看cat_more...
查看>>
mysql使用索引优化查询效率
查看>>
Salt Syndic配置
查看>>
Linux下Git和GitHub使用方法总结 (码云)
查看>>
linux 安装与卸载软件
查看>>
windows phone 浏览器
查看>>
SQL Server 百万级数据提高查询速度的方法
查看>>
汇编程序:哆瑞米发商拉西
查看>>
centos 7.3 LVS的NAT模式负载均衡实操
查看>>
Zend Server 安装记录
查看>>
算法学习之路|判断题
查看>>
mongoDB文档操作
查看>>
Swiper – 经典的移动触摸滑块插件【免费】
查看>>