【LeetCode】241. Different Ways to Add Parentheses 为运算表达式设计优先级(Medium)(JAVA)

【LeetCode】241. Different Ways to Add Parentheses 为运算表达式设计优先级(Medium)(JAVA)

题目地址: https://leetcode.com/problems/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

题目大意

给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。

解题方法

  1. 先把所有的数字和运算符有序存到两个队列里
  2. 采用递归方法,对某一运算符为中心点,分割为左右两边,左右两边分别计算出所有的结果,再拼接成结果
  3. 循环遍历运算符,分别为不同的中心点
class Solution {
    public List<Integer> diffWaysToCompute(String input) {
        List<Integer> nums = new ArrayList<>();
        List<Character> operates = new ArrayList<>();
        int num = 0;
        for (int i = 0; i < input.length(); i++) {
            char ch = input.charAt(i);
            if (ch == '+' || ch == '-' || ch == '*') {
                nums.add(num);
                operates.add(ch);
                num = 0;
            } else {
                num = num * 10 + ch - '0';
            }
        }
        nums.add(num);
        return dH(nums, operates, 0, operates.size());
    }

    public List<Integer> dH(List<Integer> nums, List<Character> operates, int start, int end) {
        List<Integer> res = new ArrayList<>();
        for (int i = start; i < end; i++) {
            char operate = operates.get(i);
            List<Integer> left = dH(nums, operates, start, i);
            List<Integer> right = dH(nums, operates, i + 1, end);
            for (int j = 0; j < left.size(); j++) {
                for (int k = 0; k < right.size(); k++) {
                    res.add(getResult(left.get(j), right.get(k), operate));
                }
            }
        }
        if (start == end) res.add(nums.get(start));
        return res;
    }

    public int getResult(int pre, int cur, char operate) {
        if (operate == '+') return pre + cur;
        if (operate == '-') return pre - cur;
        return pre * cur;
    }
}

执行耗时:1 ms,击败了100.00% 的Java用户
内存消耗:38.8 MB,击败了28.06% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值