Different Ways to Add Parentheses

加括号的不同方式

思路:分治地求出一个运算符的左边部分和右边部分的结果,将它们两两组合运算。优化的方式是用一个hash表记录所有字串的中间结果,避免重复计算。

 1 public class Solution {
 2     Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();
 3     public List<Integer> diffWaysToCompute(String input) {
 4         if (map.containsKey(input)) {
 5             return map.get(input);
 6         }
 7         
 8         List<Integer> res = new ArrayList<Integer>();
 9         if (!(input.contains("+") || input.contains("-") || input.contains("*"))) {
10             res.add(Integer.parseInt(input));
11             map.put(input, res);
12             return res;
13         }
14         for (int i = 0; i < input.length(); i++) {
15             char c = input.charAt(i);
16             if (c == '+' || c == '-' || c == '*') {
17                 String p1 = input.substring(0, i);
18                 String p2 = input.substring(i + 1, input.length());
19                 List<Integer> res1 = diffWaysToCompute(p1);
20                 List<Integer> res2 = diffWaysToCompute(p2);
21                 
22                 for (int n1 : res1) {
23                     for (int n2 : res2) {
24                         if (c == '+') {
25                             res.add(n1 + n2);
26                         } else if (c == '-') {
27                             res.add(n1 - n2);
28                         } else if (c == '*') {
29                             res.add(n1 * n2);
30                         }
31                     }
32                 }
33             }
34         }
35         map.put(input, res);
36         return res;
37     }
38 }
View Code

相关文章:

  • 2022-12-23
  • 2022-01-07
  • 2021-09-20
  • 2021-08-31
  • 2022-12-23
  • 2021-05-21
猜你喜欢
  • 2021-06-20
  • 2022-12-23
  • 2021-07-27
  • 2022-12-23
  • 2022-12-23
  • 2021-12-10
  • 2021-09-08
相关资源
相似解决方案