为运算表达式设计优先级

力扣

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
class Solution {
public List<Integer> diffWaysToCompute(String input) {
List<Integer> result = new ArrayList<>();
//终止条件
if (!input.contains("+") && !input.contains("-") && !input.contains("*")) {
result.add(Integer.valueOf(input));
return result;
}
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == '+' || input.charAt(i) == '-' || input.charAt(i) == '*') {
for (Integer left : diffWaysToCompute(input.substring(0, i))) {
for (Integer right : diffWaysToCompute(input.substring(i + 1))) {
if (input.charAt(i) == '+') {
result.add(left + right);
} else if (input.charAt(i) == '-') {
result.add(left - right);
} else if (input.charAt(i) == '*') {
result.add(left * right);
}
}
}
}
}
return result;
}
}

不同的二叉搜索树Ⅱ

力扣

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
class Solution {
public List<TreeNode> generateTrees(int n) {
if (n < 1) {
return new LinkedList<TreeNode>();
}
return generateSubtrees(1, n);
}

private List<TreeNode> generateSubtrees(int s, int e) {
List<TreeNode> res = new LinkedList<TreeNode>();
//终止条件
if (s > e) {
res.add(null);
return res;
}
for (int i = s; i <= e; i++) {
// i作为根节点
List<TreeNode> leftSubtrees = generateSubtrees(s, i - 1);
List<TreeNode> rightSubtrees = generateSubtrees(i + 1, e);
for (TreeNode left : leftSubtrees) {
for (TreeNode right : rightSubtrees) {
TreeNode root = new TreeNode(i);
root.left = left;
root.right = right;
res.add(root);
}
}
}
return res;
}
}