leetcode 553. Optimal Division

1.题目

Given a list of positive integers, the adjacent integers will perform the float division. For example, [2,3,4] -> 2 / 3 / 4.

However, you can add any number of parenthesis at any position to change the priority of operations. You should find out how to add parenthesis to get the maximum result, and return the corresponding expression in string format. Your expression should NOT contain redundant parenthesis.
给一个正整数列表,相邻数之间做浮点数除法,例如[2,3,4] 表示 2/3/4
假设可以加上任意数量的括号,求怎样加括号得到最大的结果。返回加括号后字符串形式的除法。

Example:

Input: [1000,100,10,2]
Output: “1000/(100/10/2)”

Explanation:
1000/(100/10/2) = 1000/((100/10)/2) = 200
去掉”1000/((100/10)/2)”中冗余的括号,返回结果 “1000/(100/10/2)”.

Other cases:
1000/(100/10)/2 = 50
1000/(100/(10/2)) = 50
1000/100/10/2 = 0.5
1000/100/(10/2) = 2

2.分析

自己想不出来,看了solution

假设列表为[x1,x2,x3…,xn]
除法表达式为 x1/x2/x3/x4…/xn
x1始终是分子,x2始终是分母,把x3/../xn看做一个整体y
y*x1/x2 y最大为x3*x4…*xn
所以这个题目有一个通用的答案
x1/(x2/x3/…/xn)

3.代码

string optimalDivision(vector<int>& nums) {
    if (nums.size() == 1)
        return to_string(nums[0]);
    if (nums.size() == 2)
        return to_string(nums[0]) + "/" + to_string(nums[1]);
    string res = to_string(nums[0]) + "/(" + to_string(nums[1]);
    for (int i = 2; i < nums.size(); i++)
        res += "/" + to_string(nums[i]);
    res += ")";
    return res;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值