LeetCode 241.给表达式加括号

241.给表达式加括号

Different Ways to Add Parentheses (Medium)

Leetcode / 力扣

题目描述

1
2
3
4
5
6
Input: "2-1-1".

((2-1)-1) = 0
(2-(1-1)) = 2

Output : [0, 2]

解题思路

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
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;
}
}