leetcode - 2232. Minimize Result by Adding Parentheses to Expression

Description

You are given a 0-indexed string expression of the form "+" where and represent positive integers.

Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+'.

Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them.

The input has been generated such that the original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.

Example 1:

复制代码
Input: expression = "247+38"
Output: "2(47+38)"
Explanation: The expression evaluates to 2 * (47 + 38) = 2 * 85 = 170.
Note that "2(4)7+38" is invalid because the right parenthesis must be to the right of the '+'.
It can be shown that 170 is the smallest possible value.

Example 2:

复制代码
Input: expression = "12+34"
Output: "1(2+3)4"
Explanation: The expression evaluates to 1 * (2 + 3) * 4 = 1 * 5 * 4 = 20.

Example 3:

复制代码
Input: expression = "999+999"
Output: "(999+999)"
Explanation: The expression evaluates to 999 + 999 = 1998.

Constraints:

复制代码
3 <= expression.length <= 10
expression consists of digits from '1' to '9' and '+'.
expression starts and ends with digits.
expression contains exactly one '+'.
The original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.

Solution

Try every possible position to put the parentheses.

Time complexity: o ( n 2 ) o(n^2) o(n2)

Space complexity: o ( 1 ) o(1) o(1)

Code

python3 复制代码
class Solution:
    def minimizeResult(self, expression: str) -> str:
        def get_value_from_expression(expression: str) -> int:
            left, right = expression.find('('), expression.find(')')
            res = eval(expression[left + 1: right])
            if left == 0 and right == len(expression) - 1:
                pass
            elif left == 0:
                res *= int(expression[right + 1:])
            elif right == len(expression) - 1:
                res *= int(expression[:left])
            else:
                res *= int(expression[:left]) * int(expression[right + 1:])
            return res

        left_index = []
        right_index = []
        add_index = expression.find('+')
        for i in range(len(expression)):
            if i < add_index:
                left_index.append(i)
            elif i > add_index:
                right_index.append(i + 1)
        min_val = float('inf')
        res = ''
        for l in left_index:
            for r in right_index:
                cur_expression = f'{expression[:l]}({expression[l:r]}){expression[r:]}'
                cur_value = get_value_from_expression(cur_expression)
                if cur_value < min_val:
                    min_val = cur_value
                    res = cur_expression
        return res
相关推荐
only-qi15 分钟前
leetcode2. 两数相加
算法·leetcode
鲨莎分不晴16 分钟前
拯救暗淡图像:深度解析直方图均衡化(原理、公式与计算)
人工智能·算法·机器学习
DuHz34 分钟前
242-267 GHz双基地超外差雷达系统:面向精密太赫兹传感与成像的65nm CMOS实现——论文阅读
论文阅读·物联网·算法·信息与通信·毫米波雷达
报错小能手1 小时前
数据结构 字典树
开发语言·数据结构
XLYcmy1 小时前
高级密码生成器程序详解:专门设计用于生成基于用户个人信息的密码猜测组合
开发语言·数据结构·python·网络安全·数据安全·源代码·口令安全
AI科技星1 小时前
时空的固有脉动:波动方程 ∇²L = (1/c²) ∂²L/∂t² 的第一性原理推导、诠释与验证
数据结构·人工智能·算法·机器学习·重构
2401_841495641 小时前
【LeetCode刷题】寻找重复数
数据结构·python·算法·leetcode·链表·数组·重复数
罗技1232 小时前
Easysearch 集群监控实战(下):线程池、索引、查询、段合并性能指标详解
前端·javascript·算法
一路往蓝-Anbo2 小时前
C语言从句柄到对象 (七) —— 给对象加把锁:RTOS 环境下的并发安全
java·c语言·开发语言·stm32·单片机·嵌入式硬件·算法
中國龍在廣州2 小时前
谈谈2025年人工智能现状及发展趋势分析
人工智能·深度学习·算法·自然语言处理·chatgpt·机器人·机器人学习