LeetCode:553. Optimal Division
来源:互联网 发布:树莓派的编程语言 编辑:程序博客网 时间:2024/06/05 08:28
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.
Example:
Input: [1000,100,10,2]Output: "1000/(100/10/2)"Explanation:1000/(100/10/2) = 1000/((100/10)/2) = 200However, 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 = 501000/(100/(10/2)) = 501000/100/10/2 = 0.51000/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.
题意:输出连除加括号结果最大的加括号字符串,要求不能够存在冗余括号。
分析:
直接数学分析,按照顺序计算时,最后一个除法的被除数越大并且除数越小,最终结果越大。由于所有数都是大于2的正数,所以被除数必须不包含除法,除数包含最多的除法,此时结果最大。因此结果是形如”A/(B/C/D….)。
代码如下:
class Solution { public String optimalDivision(int[] nums) { if(nums==null||nums.length==0) return ""; StringBuilder s=new StringBuilder(); s.append(nums[0]); if(nums.length==2){ return s.append("/"+nums[1]).toString(); } for(int i=1;i<nums.length;i++){ s.append("/"); if(i==1) s.append("("); s.append(nums[i]); if(i==nums.length-1) s.append(")"); } return s.toString(); }}
补充:不同的加括号的措施符合卡特兰数规律,也即后缀表达式操作数出栈次序。n+1个数,n个除号,n对括号,h(0)=0,h(1)=1,h(n)=h(0)h(n-1)+h(2)h(n-2)+….+h(n-1)h(0),h(n)=C(2n,n)-C(2n,n-1)。
遍历方法:将数据分成两部分,left和right,从1到n遍历分割位置, 如果右边数据大于1,则右边加括号。
- leetcode 553. Optimal Division
- leetcode 553. Optimal Division
- LeetCode:553. Optimal Division
- leetcode 553. Optimal Division
- [leetcode]553. Optimal Division
- [LeetCode]553. Optimal Division
- LeetCode:553. Optimal Division
- leetcode 553. Optimal Division 最优除法
- [Leetcode] 553. Optimal Division 解题报告
- 553. Optimal Division
- 553. Optimal Division
- 553. Optimal Division
- 553. Optimal Division
- 553. Optimal Division
- 553. Optimal Division
- 553. Optimal Division
- 553. Optimal Division
- 553. Optimal Division
- 第七章:存储过程
- 利用高德云图开发附近的人功能
- QFileDialog
- JAVA练习 日期时间的排序查找
- python 逐行读取文件数据
- LeetCode:553. Optimal Division
- c++ STL总结
- 实训第三天~
- android studio打开项目后一直Gradle:Resolve dependecies 'app_XXAPk'很长时间?
- uget使用aria2,出现Is aria2 shutdown的错误
- 问题 C: 二哈大定理
- 【风宇冲】Unity3D教程宝典之Shader篇:第四讲制作一个美丽的地球 + 云层颜色的一点见解
- 【populating-next-right-pointers-in-each-node-ii】
- 170907_学习测试(三)_Apache JMeter 入门(二)_JMeter脚本录制