LeetCode 241. Different Ways to Add Parentheses

原题链接在这里:https://leetcode.com/problems/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".

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

Output: [0, 2]

Example 2

Input: "2*3-4*5"

(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

Output: [-34, -14, -10, -10, 10] 

题解:

Divide and Conquer. 遇到 +, -, *号就divide直到只剩下一个数字的时候.

合并时,符号左侧substring生成的结果list 与 符号右侧substring生成的list轮番取值运算加入res中.

设a为操作数,~为操作符,对于表达式:
a~a,解空间只有 a ~ a
a~a~a 解空间为 (a~a)~a 和 a~(a~a)
a~a~a~a 解空间为 a~(解空间(a~a~a))和 (解空间(a~a~a))~a
...
因此,要求一个表达式的解空间,可以采用分治策略。例如对于2*3-4*5表达式:
解空间为:
2*解空间(3-4*5)
解空间(2*3) - 解空间(4*5)
解空间(2*3-4)* 解空间(5)
然后在对每个子解空间进行递归求解。

Note: 若是input是一个数字时, 没有运算符, 所以res是空的,此时直接添加数字。

Time Complexity: exponential. Space: O(n).

AC Java:

 1 public class Solution {
 2     public List<Integer> diffWaysToCompute(String input) {
 3         List<Integer> res = new ArrayList<Integer>();
 4         if(input == null || input.length() == 0){
 5             return res;
 6         }
 7         for(int i = 0; i<input.length(); i++){
 8             char c = input.charAt(i);
 9             //当遇到+, -, *时需要divide
10             if(c == '+' || c == '-' || c == '*'){
11                 List<Integer> left = diffWaysToCompute(input.substring(0, i)); //left是符号左边substring得到的结果
12                 List<Integer> right = diffWaysToCompute(input.substring(i+1)); //right是符号右边substring得到的结果
13                 //左右轮番取值计算加入res中
14                 for(int l : left){
15                     for(int r : right){
16                         if(c == '+'){
17                             res.add(l+r);
18                         }else if(c == '-'){
19                             res.add(l-r);
20                         }else if(c == '*'){
21                             res.add(l*r);
22                         }
23                     }
24                 }
25             }
26         }
27         //input是单独的数字时, 没遇到符号所以res是空的, 这是divide的base case, 要把这个数字加到res中
28         if(res.size() == 0){
29             res.add(Integer.valueOf(input));
30         }
31         return res;
32     }
33 }

类似Unique Binary Search Trees II.

原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4919244.html