算法设计作业15

来源:互联网 发布:jasper陈小春知乎 编辑:程序博客网 时间:2024/06/05 00:28

第十五周作业:

553. Optimal Division


解题思路:



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:

  1. The length of the input array is [1, 10].
  2. Elements in the given array will be in range [2, 1000].
  3. 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);}};