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

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

原文地址:

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]

这种问题可以使用分治法,递归去处理运算符两边的字符串,边界条件就是不再可以按照运算符分割字符串,即字符串中只包含数字。

public class DifferentWaysToAddParentheses {
public static List
diffWaysToCompute(String input) { if (input == null) return null; List
res = new ArrayList<>(); for (int i = 0; i < input.length(); i++) { if (input.charAt(i) == '+' || input.charAt(i) == '-' || input.charAt(i) == '*') { List
res1 = diffWaysToCompute(input.substring(0, i)); List
res2 = diffWaysToCompute(input.substring(i + 1)); for (int index1 = 0; index1 < res1.size(); index1++) { for (int index2 = 0; index2 < res2.size(); index2++) { if (input.charAt(i) == '+') { res.add(res1.get(index1) + res2.get(index2)); } else if (input.charAt(i) == '-') { res.add(res1.get(index1) - res2.get(index2)); } else { res.add(res1.get(index1) * res2.get(index2)); } } } } } if (res == null || res.size() == 0) res.add(Integer.valueOf(input)); return res; } public static void main(String[] args) { String input = "2*3-4*5"; System.out.println(diffWaysToCompute(input)); }}

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

你可能感兴趣的文章
通过Spring Boot三分钟创建Spring Web项目
查看>>
Spring的IoC(依赖注入)原理
查看>>
Guava快速入门
查看>>
Java编程基础:static的用法
查看>>
Java编程基础:抽象类和接口
查看>>
Java编程基础:异常处理
查看>>
Java编程基础:了解面向对象
查看>>
新一代Java模板引擎Thymeleaf
查看>>
Spring MVC中使用Thymeleaf模板引擎
查看>>
Spring Boot构建简单的微博应用
查看>>
Spring处理表单提交
查看>>
Spring MVC异常处理
查看>>
Leetcode 1180. Count Substrings with Only One Distinct Letter [Python]
查看>>
PHP 7 的五大新特性
查看>>
php使用 memcache 来存储 session
查看>>
php实现socket(转)
查看>>
PHP底层的运行机制与原理
查看>>
深入了解php底层机制
查看>>
PHP中的stdClass 【转】
查看>>
XHProf-php轻量级的性能分析工具
查看>>