* [1. 给表达式加括号](#1-给表达式加括号) # 1. 给表达式加括号 [241. Different Ways to Add Parentheses (Medium)](https://leetcode.com/problems/different-ways-to-add-parentheses/description/) ```html Input: "2-1-1". ((2-1)-1) = 0 (2-(1-1)) = 2 Output : [0, 2] ``` ```java public List diffWaysToCompute(String input) { List ways = new ArrayList<>(); for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (c == '+' || c == '-' || c == '*') { List left = diffWaysToCompute(input.substring(0, i)); List 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; } ```
欢迎关注我的公众号 CyC2018,这里有最核心的高频基础知识面试题,后台回复关键字 📚 “资料” 可领取复习大纲 ,帮你理清多而杂的面试知识点。