首页 > 代码库 > Different Ways to Add Parentheses

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, 跟 Leetcode: Unique Binary Search Trees II 很像

在input string里遍历各个operator, 依据每个operator分成左右子串,左右子串做递归返回所有可能的results,然后全排列。

注意很巧妙的一点在于寻找operator来划分,然后如果像20-23行那样没有划分成功(因为每找到operator)则Inter.parseInt(input),这样省去了计算多位integer的工夫。比如input.charAt(i)=2, input.charAt(i+1)=3, 我们不需要再自己计算得到23. 

 

dfs 调用自身即可,

分治法--后序遍历返回值, 先序遍历输入值. 画图自下而上返回.

注意 叶结点的处理

public class Solution {
    public List<Integer> diffWaysToCompute(String input) {
        List<Integer> res = new ArrayList<Integer>();
        if (input==null || input.length()==0) return res;
        
        for (int i=0; i<input.length(); i++) { //结束条件 i  = input.length()
            char c = input.charAt(i);    
            if (!isOperator(c)) continue;  //递归条件
            List<Integer> left = diffWaysToCompute(input.substring(0, i));
            List<Integer> right = diffWaysToCompute(input.substring(i+1));
			//递归条件---返回值
            for (int j=0; j<left.size(); j++) {
                for (int k=0; k<right.size(); k++) {
                    int a = left.get(j);
                    int b = right.get(k);
                    res.add(calc(a,b,c));
                }
            }
        }
        // 叶节点的处理
        if (res.size() == 0) { //input is not null or size==0, but res.size()==0, meaning input is just a number
            res.add(Integer.valueOf(input));
} return res; } public boolean isOperator(char c) { if (c==‘+‘ || c==‘-‘ || c==‘*‘) return true; return false; } public int calc(int a, int b, char c) { int res = Integer.MAX_VALUE; switch(c) { case ‘+‘: res = a+b; break; case ‘-‘: res = a-b; break; case ‘*‘: res = a*b; break; } return res; } }

  

Different Ways to Add Parentheses