Leetcode 0241: 为运算表达式设计优先级 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: “23-45”
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

Example 3:

Input: nums = [1,-1], k = 1
Output: [1,-1]

Example 4:

Input: nums = [9,11], k = 2
Output: [11]

Example 5:

Input: nums = [4,-2], k = 2
Output: [4]

Constraints:

1 <= nums.length <= 105
-104 <= nums[i] <= 104
1 <= k <= nums.length

Time complexity: O O O( C n C_{n} Cn)
卡特兰数 分治法

  1. 可以将整个字符串表达式看成是不同的二叉树的中序遍历,子节点位数,同以括号内的数代表有同一个最近根结点。则不同的二叉树中序遍历就是是该字符串的不同表达式所展现的结果。
  2. 遍历整个字符串,当遇到运算符号’+’,’-’,或者’ * '时,可以以该运算符号字符为根结点,将左半边[0,i - 1]作为左子树,将右边边[i + 1,n - 1]作为右子树,并两个子树递归下去,搜索出所有满足题意的情况。
  3. 左子树的集合中的任意二叉树 和 右子树集合中的任意二叉树 都能与 当前根结点i进行拼接形成新的二叉树,即左半边部分的字符串通过不同方式的加括号形成的值的集合 和 左半边部分的字符串通过不同方式的加括号形成的值的集合 可以再次通过当前字符’+’,’-’,’*'加括号进行合并,形成新的集合集
  4. 当递归的字符串只是一个数时,直接返回该数
class Solution {
    
    

    public List<Integer> diffWaysToCompute(String input) {
    
    
        List<Integer> res = new ArrayList<>();
        for (int i=0; i<input.length(); i++) {
    
    
            char op = input.charAt(i);
            if (op == '-' ||
                op == '*' ||
                op == '+' ) {
    
    
                String part1 = input.substring(0, i);
                String part2 = input.substring(i+1);
                List<Integer> part1Res = diffWaysToCompute(part1);
                List<Integer> part2Res = diffWaysToCompute(part2);
                for (Integer p1: part1Res) {
    
    
                    for (Integer p2:part2Res) {
    
    
                        int tmp = 0;
                        if(op == '-'){
    
    
                            tmp = p1-p2;
                        }else if(op == '*'){
    
    
                            tmp = p1*p2;
                        }else if(op == '+' ){
    
    
                            tmp = p1+p2;
                        }
                        res.add(tmp);
                    }
                }
            }
        }
        if (res.size() == 0) {
    
    
            res.add(Integer.valueOf(input));
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43946031/article/details/114024505