[LeetCode] 241. Different Ways to Add Parentheses

博客围绕LeetCode上一道字符串题目展开,题目要求给出包含数字和操作符的字符串所有不同计算顺序的结果。解题采用递归法,将字符串按符号位置分为三部分,通过逐层求解子问题,计算出全部结果,且结果集允许有重复元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接:https://leetcode.com/problems/different-ways-to-add-parentheses/

1. 题目介绍

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

2. 解题思路

递归法

这个题可以使用递归,逐步求解子问题。和 95. Unique Binary Search Trees II 的解题思路很类似。

按照符号的不同位置,我们可以将字符串分为三个部分,中间是操作符,左边和右边都是子串。比如:

Input: "2*3-4*5"

可以分为:

2 * (3-4*5)  或者 (2*3) - (4*5) 或者 (2*3-4) * 5

这样,一个字符串的结果集,就是每一个左子串的结果和每一个右子串的结果进行运算的集合。我们使用这种方法逐层求解,最终可以计算出全部的结果。
需要注意的是,这个题目中允许结果集中有重复的元素。
实现代码

class Solution {
    public List<Integer> diffWaysToCompute(String input) {
        List<Integer> ans = new ArrayList<>();
        int N = input.length();
        if(N == 0){
            return ans;
        }
        
        for(int i = 0 ; i < N ; i++){
            char x = input.charAt(i);
            if(x == '+' || x == '*' || x == '-'){
                List<Integer> left  = diffWaysToCompute(input.substring( 0 ,i));
                List<Integer> right = diffWaysToCompute(input.substring(i+1,N));
                
                for(int j : left){
                    for(int k : right){
                        int temp = 0;
                        if(x == '+'){ temp = j + k; }
                        else if(x == '*'){ temp = j * k; }
                        else if(x == '-'){ temp = j - k; }
                        
                        ans.add(temp);
                    }
                }
            }
        }
        
        //针对没有运算符号只有数字的情况,这个数字可能只有一位,也可能是有多位
        if(ans.isEmpty() == true){
            ans.add( Integer.parseInt(input) );
        }
        return ans;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值