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

直接用分治法就可以解决。但是分治法存在重复计算,因此利用hashmap来起到记忆功能。

import java.util.*;

class Solution {
    
    private Map> map = new HashMap<>();
    
    public List diffWaysToCompute(String input) {
        
        if(map.containsKey(input)) return map.get(input);
        
        List res = new ArrayList<>();
        
        for(int i = 0;i lefts = diffWaysToCompute(input.substring(0,i));
            List rights = diffWaysToCompute(input.substring(i+1,input.length()));
            for(int left:lefts){
                for(int right:rights){
                    switch(input.charAt(i)){
                        case '+':
                            res.add(left+right);
                            break;
                        case '-':
                            res.add(left-right);
                            break;
                        case '*':
                            res.add(left*right);
                            break;
                        case '/':
                            res.add(left/right);
                            break;
                    }
                }
            }
        }
        
        if(res.isEmpty()){
            res.add(Integer.valueOf(input));
        }
        
        map.put(input,res);
        
        return res;
    }
    
}

 

你可能感兴趣的:(LeetCode 241. Different Ways to Add Parentheses)