[LeetCode] 241. Different Ways to Add Parentheses

时间:2020-07-11
本文章向大家介绍[LeetCode] 241. Different Ways to Add Parentheses,主要包括[LeetCode] 241. Different Ways to Add Parentheses使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +- and *.

Example 1:

Input: "2-1-1"
Output: [0, 2]
Explanation: 
((2-1)-1) = 0 
(2-(1-1)) = 2

Example 2:

Input: "2*3-4*5"
Output: [-34, -14, -10, -10, 10]
Explanation: 
(2*(3-(4*5))) = -34 
((2*3)-(4*5)) = -14 
((2*(3-4))*5) = -10 
(2*((3-4)*5)) = -10 
(((2*3)-4)*5) = 10

为运算表达式设计优先级。题意是给一个以字符串表示的运算表达式,请为其添加括号,展示出所有可能的解。运算符号只有+,-,*。

思路是分治法。在实际操作的过程中,不需要真的添加括号,而是会通过分治的办法以达到括号能实现的运算优先级的目的。具体的思路是,遍历input字符串,每当遇到一个运算符号,就把这个符号的左边和右边分开,接着往下分治计算。在分治后的两个list中,挑出两个数字两两计算。最后把计算结果加入最后的list。

时间 - ?

空间O(n)

Java实现

 1 class Solution {
 2     public List<Integer> diffWaysToCompute(String input) {
 3         List<Integer> res = new ArrayList<>();
 4         for (int i = 0; i < input.length(); i++) {
 5             char c = input.charAt(i);
 6             if (c == '-' || c == '*' || c == '/') {
 7                 String a = input.substring(0, i);
 8                 String b = input.substring(i + 1);
 9                 List<Integer> aList = diffWaysToCompute(a);
10                 List<Integer> bList = diffWaysToCompute(b);
11                 for (int x : aList) {
12                     for (int y : bList) {
13                         if (c == '-') {
14                             res.add(x - y);
15                         } else if (c == '+') {
16                             res.add(x + y);
17                         } else if (c == '*') {
18                             res.add(x * y);
19                         }
20                     }
21                 }
22             }
23         }
24         if (res.size() == 0) {
25             res.add(Integer.valueOf(input));
26         }
27         return res;
28     }
29 }

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/13282852.html