Problem:

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]

Analysis:

At first glance, there problem is really complex!!! But once you get the point, you feel so surprised that this problem is so elegant and simple.

Basic idea: divide and conquer.
Assumption 1: input = a - b + c + e * f
How could we add parenthess onto the input string? Add all parenthesses at one time?
That's too complex...
How about add parenthess recursively???
For each input, we only add two parenthess, then pass the task of adding parenthess into next level.
Step 1: input = (a - b) + (c + e * f)
Step 2: add_compute(a - b), add_compute(c + e * f) Key 1: the valid way to add bracket, choice a operator, then cut into two parts.
if (c == '+' || c == '-' || c == '*') {
List<Integer> left = diffWaysToCompute(input.substring(0, i));
List<Integer> right = diffWaysToCompute(input.substring(i+1, input.length()));
...
} Key 2: Use the number string(not include operand) as base case! Since we always divide the input string against a operator, we must be able to reach the base case: "input is a string representation of number".
if (!(input.contains("+") || input.contains("-") || input.contains("*"))) {
ret.add(Integer.valueOf(input));
return ret;
}
Note: iff use input.indexOf('+') must in the form of input.indexOf('+') != -1. Key 3: use operand over the return value from child branch.
for (int m = 0; m < left.size(); m++) {
for (int n = 0; n < right.size(); n++) {
int num1 = left.get(m);
int num2 = right.get(n);
if (c == '+')
ret.add(num1 + num2);
else if (c == '-')
ret.add(num1 - num2);
else
ret.add(num1 * num2);
}
}

Wrong solution:

public class Solution {
public List<Integer> diffWaysToCompute(String input) {
List<Integer> ret = new ArrayList<Integer> ();
int len = input.length();
if (len == 1) {
ret.add(Integer.valueOf(input.charAt(0) + ""));
return ret;
}
for (int i = 0; i < len; i++) {
char c = input.charAt(i);
if (c == '+' || c == '-' || c == '*') {
List<Integer> left = diffWaysToCompute(input.substring(0, i));
List<Integer> right = diffWaysToCompute(input.substring(i+1, input.length()));
for (int m = 0; m < left.size(); m++) {
for (int n = 0; n < right.size(); n++) {
if (c == '+')
ret.add(m + n);
else if (c == '-')
ret.add(m - n);
else
ret.add(m * n);
}
}
}
}
return ret;
}
}

Mistake analysis:

Mistake 1:
The stereotype of using CharAt(). In this problem, a number could be represented by using multi charcacters together.
Fix:
if (!(input.contains("+") || input.contains("-") || input.contains("*"))) {
ret.add(Integer.valueOf(input));
return ret;
} Mistake 2:
Forget to get the number from return list, but use index.
Fix:
int num1 = left.get(m);
int num2 = right.get(n);
if (c == '+') {
...
}

Solution:

public class Solution {
public List<Integer> diffWaysToCompute(String input) {
List<Integer> ret = new ArrayList<Integer> ();
int len = input.length();
if (!(input.contains("+") || input.contains("-") || input.contains("*"))) {
ret.add(Integer.valueOf(input));
return ret;
}
for (int i = 0; i < len; i++) {
char c = input.charAt(i);
if (c == '+' || c == '-' || c == '*') {
List<Integer> left = diffWaysToCompute(input.substring(0, i));
List<Integer> right = diffWaysToCompute(input.substring(i+1, input.length()));
for (int m = 0; m < left.size(); m++) {
for (int n = 0; n < right.size(); n++) {
int num1 = left.get(m);
int num2 = right.get(n);
if (c == '+')
ret.add(num1 + num2);
else if (c == '-')
ret.add(num1 - num2);
else
ret.add(num1 * num2);
}
}
}
}
return ret;
}
}

[LeetCode#241]Different Ways to Add Parentheses的更多相关文章

  1. LN : leetcode 241 Different Ways to Add Parentheses

    lc 241 Different Ways to Add Parentheses 241 Different Ways to Add Parentheses Given a string of num ...

  2. [LeetCode] 241. Different Ways to Add Parentheses 添加括号的不同方式

    Given a string of numbers and operators, return all possible results from computing all the differen ...

  3. (medium)LeetCode 241.Different Ways to Add Parentheses

    Given a string of numbers and operators, return all possible results from computing all the differen ...

  4. leetcode@ [241] Different Ways to Add Parentheses (Divide and Conquer)

    https://leetcode.com/problems/different-ways-to-add-parentheses/ Given a string of numbers and opera ...

  5. LeetCode 241. Different Ways to Add Parentheses为运算表达式设计优先级 (C++)

    题目: Given a string of numbers and operators, return all possible results from computing all the diff ...

  6. leetcode 96. Unique Binary Search Trees 、95. Unique Binary Search Trees II 、241. Different Ways to Add Parentheses

    96. Unique Binary Search Trees https://www.cnblogs.com/grandyang/p/4299608.html 3由dp[1]*dp[1].dp[0]* ...

  7. 241. Different Ways to Add Parentheses

    241. Different Ways to Add Parentheses https://leetcode.com/problems/different-ways-to-add-parenthes ...

  8. 【LeetCode】241. Different Ways to Add Parentheses

    Different Ways to Add Parentheses Given a string of numbers and operators, return all possible resul ...

  9. LC 241. Different Ways to Add Parentheses

    Given a string of numbers and operators, return all possible results from computing all the differen ...

随机推荐

  1. Spring for Apache Kafka

    官方文档详见:http://docs.spring.io/spring-kafka/docs/1.0.2.RELEASE/reference/htmlsingle/ Authors Gary Russ ...

  2. DataGrid列的合并

    /// <summary> /// DataGrid列的合并 /// 注意:1.DataGrid在绑定的时候进行分组和排序,才能让相同的行放在一起 /// 2.方法应用的时机,应该在Dat ...

  3. (转)C# 中的委托和事件

    来源:http://www.tracefact.net/CSharp-Programming/Delegates-and-Events-In-CSharp.aspx 引言 委托 和 事件在 .Net ...

  4. SQL查询一些浅薄的结论

    一些简单的测试结论 在本机经过一些简单的测试,记录数6W条,得出以下结论,不同的硬件环境和数据记录数,可能会有不一样的结论 1.in, or, exists, like, not in , not e ...

  5. window.event对象详细介绍

    1.event代表事件的状态,例如触发event对象的元素.鼠标的位置及状态.按下的键等等.event对象只在事件发生的过程中才有效.event的某些属性只对特定的事件有意义.比如,fromEleme ...

  6. Net的struct的内存对齐问题

    很少有人谈起struct的内存对齐问题, 就是在很多C#书中, 也很少提及. 但在实际应用中, 如果不注意内存对齐, struct比较大的话, 则会浪费一定的内存.    先从一个实例看起. publ ...

  7. Windows phone 之Image控件

    wp目前支持的图片格式为png和jpeg ,我们可以通过设置Source属性设置图片源. 还有两个属性是:Stretch,Opacity Stretch属性 image的拉伸行为有此属性决定,此属性是 ...

  8. Android学习2--项目文件列表简单分析

    使用Eclipse创建的默认项目文件列表如下: src:src目录是Android工程的源程序目录,该目录用于存放Java项目的源代码 gen:gen目录存放所有自动生成的文件,在这个目录中最关键的文 ...

  9. 问题:Bringing up interface eth0: Device eth0 does not seem to be present,delaying initialization. [FAILED]—— 找不到网卡。

    克隆虚拟机的时候或其他情况出现以下问题(命令service network restart):   Bringing up interface eth0:  Device eth0 does not ...

  10. StrongReference

    原创作品:未经本人允许,不得转载前段时间写项目时遇到了一个问题,就是从网络获取图片资源的问题,总是出现OOM异常,经过几天的努力,终于处理的还算是可以使用,OOM的处理一直都是很头疼的问题.对于三级缓 ...