2019-03-27 20:57:37 +08:00
|
|
|
|
<!-- GFM-TOC -->
|
|
|
|
|
* [1. 给表达式加括号](#1-给表达式加括号)
|
|
|
|
|
<!-- GFM-TOC -->
|
2019-03-08 20:31:07 +08:00
|
|
|
|
|
2019-03-27 20:57:37 +08:00
|
|
|
|
|
|
|
|
|
# 1. 给表达式加括号
|
|
|
|
|
|
|
|
|
|
[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:57:37 +08:00
|
|
|
|
Input: "2-1-1".
|
2019-03-08 20:31:07 +08:00
|
|
|
|
|
2019-03-27 20:57:37 +08:00
|
|
|
|
((2-1)-1) = 0
|
|
|
|
|
(2-(1-1)) = 2
|
2019-03-08 20:31:07 +08:00
|
|
|
|
|
2019-03-27 20:57:37 +08:00
|
|
|
|
Output : [0, 2]
|
2019-03-08 20:31:07 +08:00
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
```java
|
2019-03-27 20:57:37 +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
|
|
|
|
}
|
|
|
|
|
```
|
2019-03-27 20:57:37 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
</br><div align="center">⭐️欢迎关注我的公众号 CyC2018,在公众号后台回复关键字 📚 **资料** 可领取复习大纲,这份大纲是我花了一整年时间整理的面试知识点列表,不仅系统整理了面试知识点,而且标注了各个知识点的重要程度,从而帮你理清多而杂的面试知识点。可以说我基本是按照这份大纲来进行复习的,这份大纲对我拿到了 BAT 头条等 Offer 起到很大的帮助。你们完全可以和我一样根据大纲上列的知识点来进行复习,就不用看很多不重要的内容,也可以知道哪些内容很重要从而多安排一些复习时间。</div></br>
|
|
|
|
|
<div align="center"><img width="180px" src="https://cyc-1256109796.cos.ap-guangzhou.myqcloud.com/%E5%85%AC%E4%BC%97%E5%8F%B7.jpg"></img></div>
|