Different Ways to Add Parentheses
来源:互联网 发布:mac os x 10.11黑苹果 编辑:程序博客网 时间:2024/06/05 11:54
原文地址:https://leetcode.com/problems/different-ways-to-add-parentheses/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]
这种问题可以使用分治法,递归去处理运算符两边的字符串,边界条件就是不再可以按照运算符分割字符串,即字符串中只包含数字。
public class DifferentWaysToAddParentheses { public static List<Integer> diffWaysToCompute(String input) { if (input == null) return null; List<Integer> res = new ArrayList<>(); for (int i = 0; i < input.length(); i++) { if (input.charAt(i) == '+' || input.charAt(i) == '-' || input.charAt(i) == '*') { List<Integer> res1 = diffWaysToCompute(input.substring(0, i)); List<Integer> 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)); }}
阅读全文
0 0
- Different Ways to Add Parentheses
- Different Ways to Add Parentheses
- Different Ways to Add Parentheses
- Different Ways to Add Parentheses
- Different Ways to Add Parentheses
- Different Ways to Add Parentheses
- Different Ways to Add Parentheses
- Different Ways to Add Parentheses
- Different Ways to Add Parentheses
- Different Ways to Add Parentheses
- Different Ways to Add Parentheses
- Different Ways to Add Parentheses
- different-ways-to-add-parentheses
- Different Ways to Add Parentheses
- Different Ways to Add Parentheses
- Different Ways to Add Parentheses
- Different Ways to Add Parentheses
- Different Ways to Add Parentheses
- 一、创建Assetbundle 在unity3d开发的游戏中,无论模型,音频,还是图片等,我们都做成Prefab,然后打包成Assetbundle,方便我们后面的使用,来达到资源的更新。
- 日期控件
- Linux内存清理
- 二叉搜索树转化为双向链表
- mysql建表date类型不能设置默认值
- Different Ways to Add Parentheses
- 虽然不简单但还是要学的JavaWeb—配置环境
- 学习笔记之初识Python
- c#操作excel文件模板
- Joda-Time用户指导
- 执行mvn 报错 source-1.5 中不支持 diamond运算符
- 解析xml的几种方法
- STL中set用法详解
- Java学习笔记(混乱)