算法设计作业15
来源:互联网 发布:jasper陈小春知乎 编辑:程序博客网 时间:2024/06/05 00:28
第十五周作业:
553. Optimal Division
解题思路:
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.
思路:这道题乍看之下很有难度,要判断得到的商的最大值,同时还不能有冗余括号,这一下就能考虑到很多种情况。但是经过仔细思考判断,由公式我们可以得知,a/(b/c/d/e/...)=a/b*c*d*e*... 在第一个被除数和第一个除数无法换位的情况下,后续所做的都是大于2的乘法,因此除了只有1个数和2个数的情况,其他情况我们都可以按照同样的处理模式来处理。
那么要如何证明呢,因为我们知道每一个数都是大于2的,所以乘的数越多肯定得到的结果就越大,被除数也是确定的,而这道题的特点也保证了无论如何加括号,第一个数和第二个数之间也不可能是相乘的关系。所以这个判断是合理的。
代码如下:
class Solution {public:string optimalDivision( vector<int> & nums ){string result;if ( nums.size() == 1 )result = to_string( nums[0] );else if ( nums.size() == 2 ){result= to_string( nums[0] );result+= "/";result+= to_string( nums[1] );}else {result= to_string( nums[0] );result+= "/";result+= "(";for ( int i = 1; i < nums.size() - 1; i++ ){result+= to_string( nums[i] );result+= "/";}result+= to_string( nums[nums.size() - 1] );result+= ")";}return(result);}};
- 算法设计作业15
- 算法设计作业;贪心;
- 算法设计作业1
- 算法设计作业2
- 算法设计作业3
- 算法设计作业4
- 算法设计作业5
- 算法设计作业6
- 算法设计作业7
- 算法设计作业8
- 算法设计作业9
- 算法设计作业10
- 算法设计作业11
- 算法设计作业12
- 算法设计作业13
- 算法设计作业14
- 算法设计作业16
- 算法设计作业17
- 金币阵列问题
- android 基于FFmpeg视频解码器
- 6.0后,全局悬浮窗或者弹窗不显示的解决办法
- Java和C/C++进行DES/AES密文传输
- 众数问题
- 算法设计作业15
- 洛谷 P1566 加等式
- [ACM] HDU 2025 查找最大元素
- 39级台阶问题
- 132. Palindrome Partitioning II (动态规划)
- 数位dp总结
- Java Swing事件处理——键盘事件及监听处理 KeyListener 按键测试
- 连续邮资问题
- javascript 字符串对象方法