LeetCode 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]

题目解答

解题思路

分治法
对于输入字符串,若其中有运算符,则将其分为两部分,分别递归计算其值,然后将左值集合与右值集合进行交叉运算,将运算结果放入结果集中;若没有运算符,则直接将字符串转化为整型数放入结果集中。

代码实现

public class Solution {

    //缓存
    Map<String, List<Integer>> map = new HashMap<>();
    public List<Integer> diffWaysToCompute(String input) {
        if(input == null)
            return new ArrayList<>();
        if(map.containsKey(input))
            return map.get(input);
        int lenOfInput = input.length();
        List<Integer> result = new ArrayList<>();
        for(int i = 0; i < lenOfInput; i++) {
            char c = input.charAt(i);
            if(c == '+' || c == '-' || c == '*') {
                List<Integer> lefts = diffWaysToCompute(input.substring(0, i));
                List<Integer> rights = diffWaysToCompute(input.substring(i+1));
                for(int left : lefts) {
                    for(int right : rights) {
                        switch(c) {
                            case '+':
                                result.add(left+right);
                                break;
                            case '-':
                                result.add(left-right);
                                break;
                            case '*':
                                result.add(left*right);
                                break;
                            default:
                        }
                    }
                }
            }
        }
        if(result.isEmpty())
            result.add(Integer.parseInt(input));
        map.put(input, result);
        return result;
    }
}

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