博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
553. Optimal Division(python+cpp)
阅读量:3700 次
发布时间:2019-05-21

本文共 2092 字,大约阅读时间需要 6 分钟。

题目:

Given a list of positive integers, the adjacent integers will performthe 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 containredundant parenthesis.
Example:

Input: [1000,100,10,2] Output: "1000/(100/10/2)" Explanation:1000/(100/10/2) = 1000/((100/10)/2) = 200 However, the bold parenthesis in "1000/((100/10)/2)" are redundant,  since they don't influence the operation priority. So you should return "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

Note:

The length of the input array is [1, 10].
Elements in the given array will be in range [2, 1000].
There is only one optimal division for each test case.

解释:

在任何位置加括号来改变算数的优先级,以得到最大的结果,最终的式子以字符串的形式给出~
这道题非常tricky,我们注意到除了第一个除数之外,后面的数都可以转变为乘积!!!
拿样例来说:
1000/(100/10/2) == (1000*10*2)/(100)
所以,我们只需要考虑三种情况:
1.只有一个数,直接返回;
2.有两个数,第一个除以第二个返回;
3.有三个及以上的数,把第二个数后面的所有数和第一个数全部乘起来,最后除以第二个数,成起来的表现就是直接连除,最外层用括号包起来。(因为note当中说明了,给的数字都是[2,1000]的,所以第二个数后面的所有数乘起来都只会让结果变大)。
python代码:

class Solution(object):    def optimalDivision(self, nums):        """        :type nums: List[int]        :rtype: str        """        len_nums=len(nums)        if len_nums==1:            return str(nums[0])        elif len_nums==2:            return '%s/%s'%(str(nums[0]),str(nums[1]))        else:            return '%s/%s'%(str(nums[0]),'(%s)'%'/'.join([str(i) for i in nums[1:]]))

c++代码:

class Solution {
public: string optimalDivision(vector
& nums) {
int len_nums=nums.size(); if (len_nums==1) return to_string(nums[0]); else if (len_nums==2) return to_string(nums[0])+"/"+to_string(nums[1]); else {
string result=to_string(nums[0])+"/("; for (int i=1;i

总结:

注意,运算符的结合方向是“自左向右”,即运算对象先与左边的运算符结合,例如100/10/5的结果是2,而不是100/(10/5)==50

转载地址:http://rglcn.baihongyu.com/

你可能感兴趣的文章
UDP、TCP协议——Linux网络编程
查看>>
HTTP、HTTPS协议——Linux网络编程
查看>>
string类——C++
查看>>
SpringMVC入门(springMVC的环境配置和入门程序以及简单的流程)
查看>>
PigyChan_LeetCode 725. 分隔链表
查看>>
PigyChan_LeetCode 2. 两数相加
查看>>
PigyChan_LeetCode 面试题 02.08. 环路检测
查看>>
PigyChan_LeetCode 109. 有序链表转换二叉搜索树
查看>>
PigyChan_LeetCode 83. 删除排序链表中的重复元素
查看>>
PigyChan_LeetCode 82. 删除排序链表中的重复元素 II
查看>>
PigyChan_LeetCode 143. 重排链表
查看>>
PigyChan_LeetCode 24. 两两交换链表中的节点
查看>>
PigyChan_LeetCode 445. 两数相加 II
查看>>
暑期实习offer比较 完美世界,灵犀互娱
查看>>
python3-matplotlib自学笔记
查看>>
ROS机器人操作系统入门--(一)ROS介绍与安装
查看>>
Wifi密码攻击实验
查看>>
电脑安装双系统——kali操作系统安装,转连接,但是后面有一些补充,个人安装碰到的问题
查看>>
cryptool1使用教程
查看>>
java+serlvet+ajax+session实现登录注销
查看>>