parentheses - 241. Different Ways to Add Parentheses

时间:2022-07-25
本文章向大家介绍parentheses - 241. Different Ways to Add Parentheses,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
  1. 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

思路:

题目意思是给一个字符串只含有加减乘字符和数字,让添加括号,计算出等式的结果,返回所有的结果,这种返回所有结果的题目,多半就是使用回溯来做,不同的是,这里的回溯是有记忆的回溯,解题思路就是根据标点符号进行切割字符串,然后递归求解,求解两部分的笛卡尔积。(可以用一个map来记录字符串计算结果,如果计算过就直接返回。来减少计算量。)

代码:

java:

class Solution {

    
    private Map<String, List<Integer>> mem = new HashMap<>();
    
    public List<Integer> diffWaysToCompute(String input) {
        if (mem.containsKey(input)) return mem.get(input);
        
        List<Integer> res = new ArrayList<>();
        
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (!(c == '+' || c == '-' || c == '*')) continue;
            
            List<Integer> left = diffWaysToCompute(input.substring(0, i));
            List<Integer> right = diffWaysToCompute(input.substring(i+1));
            
            // 笛卡尔积
            for (Integer l : left) {
                for (Integer r : right) {
                    int temp = 0;
                    if (c == '+') temp = r + l;
                    else if (c == '-') temp = l - r;
                    else /*(c == '*')*/ temp = l * r;
                    res.add(temp);
                }
            }
        }
        
        if (res.isEmpty()) res.add(Integer.parseInt(input));
        mem.put(input, res);
        return res;
    }
}