2019-03-27 20:46:47 +08:00
|
|
|
|
# 1. 给表达式加括号
|
2019-03-08 20:31:07 +08:00
|
|
|
|
|
2019-03-27 20:46:47 +08:00
|
|
|
|
[241. Different Ways to Add Parentheses (Medium)](https://leetcode.com/problems/different-ways-to-add-parentheses/description/)
|
2019-03-08 20:31:07 +08:00
|
|
|
|
|
|
|
|
|
```html
|
2019-03-27 20:46:47 +08:00
|
|
|
|
Input: "2-1-1".
|
2019-03-08 20:31:07 +08:00
|
|
|
|
|
2019-03-27 20:46:47 +08:00
|
|
|
|
((2-1)-1) = 0
|
|
|
|
|
(2-(1-1)) = 2
|
2019-03-08 20:31:07 +08:00
|
|
|
|
|
2019-03-27 20:46:47 +08:00
|
|
|
|
Output : [0, 2]
|
2019-03-08 20:31:07 +08:00
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
```java
|
2019-03-27 20:46:47 +08:00
|
|
|
|
public List<Integer> diffWaysToCompute(String input) {
|
|
|
|
|
List<Integer> ways = new ArrayList<>();
|
|
|
|
|
for (int i = 0; i < input.length(); 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));
|
|
|
|
|
for (int l : left) {
|
|
|
|
|
for (int r : right) {
|
|
|
|
|
switch (c) {
|
|
|
|
|
case '+':
|
|
|
|
|
ways.add(l + r);
|
|
|
|
|
break;
|
|
|
|
|
case '-':
|
|
|
|
|
ways.add(l - r);
|
|
|
|
|
break;
|
|
|
|
|
case '*':
|
|
|
|
|
ways.add(l * r);
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if (ways.size() == 0) {
|
|
|
|
|
ways.add(Integer.valueOf(input));
|
|
|
|
|
}
|
|
|
|
|
return ways;
|
2019-03-08 20:31:07 +08:00
|
|
|
|
}
|
|
|
|
|
```
|