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:

  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.

题意:输出连除加括号结果最大的加括号字符串,要求不能够存在冗余括号。
分析:
直接数学分析,按照顺序计算时,最后一个除法的被除数越大并且除数越小,最终结果越大。由于所有数都是大于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,则右边加括号。

原创粉丝点击