Different Ways to Add Parentheses

本文介绍了一种使用动态规划解决给定包含数字和运算符的字符串,返回所有可能计算结果的方法。通过避免重复计算子问题,显著提升了算法效率。

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

题目如下:

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]

解法:

这道题首先想到的是采用递归的分治方法解,但这种方法明显存在大量子问题重复计算的情况。单用递归实现最终运行时间只打败了16%的提交结果,考虑到性能的优化,于是采用动态规划的方法重新实现一遍,采用一个hashmap记录已经算出的子问题结果,在遇到已经算出结果的子问题时直接从hashmap中get到计算结果。需要引入一个helper函数,将该hashmap作为实参传入helper函数,随着helper函数的递归不断向hashmap中加入新的子问题结果。

public class Solution {
    public List<Integer> diffWaysToCompute(String input) {
        Map<String, List<Integer>> memory = new HashMap<String, List<Integer>>();
        return helper(input, memory);
    }
    public List<Integer> helper(String input, Map<String, List<Integer>> memory) {
        List<Integer> rst = new LinkedList<Integer>();
        int len = input.length();
        for (int i = 0; i < len; i++) {
            if (input.charAt(i) == '+' || input.charAt(i) == '-' || input.charAt(i) == '*') {
                String s1 = input.substring(0, i);
                String s2 = input.substring(i + 1, len);
                List<Integer> p1 = memory.get(s1);
                List<Integer> p2 = memory.get(s2);
                if (p1 == null) {
                    p1 = helper(s1, memory);
                }
                if (p2 == null) {
                    p2 = helper(s2, memory);
                }
                for (int m: p1) {
                    for (int n: p2) {
                        switch (input.charAt(i)) {
                            case '+':
                                rst.add(m + n);
                                break;
                            case '-':
                                rst.add(m - n);
                                break; 
                            case '*':
                                rst.add(m * n);
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
        }
        if (rst.size() == 0) {
            rst.add(Integer.valueOf(input));
        }
        memory.put(input, rst);
        return rst;
    }
}

采用动态规划的方法,最终运行时间打败了88.56%的提交结果,大大提高了运行速度。

 

转载于:https://www.cnblogs.com/shinning/p/5311603.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值