Leetcode-553

导读:本篇文章讲解 Leetcode-553,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

###题目
题目链接

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) = 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.

###分析
题目大意是给出一个整数数组(其实就是一个用除号连接的算式),现在可以在任意的位置插入小括号,这样就改变了数字原本的运算顺序,求解一种添加小括号的方法使整个算式计算的结果最大。
显然直接计算会有难度,分析如下:

原本的数组组成的算式可以表示为:a/b/c/d…
要使整个分式的结果最大,那么只需要让分子尽量大,分母尽量小就可以了,由于a一定会在分子,b一定会在分母上(无论括号加在什么地方),这样的算式总是可以表示为:
an1n2…/bm1m2
如果有一种划分的方法,使分母只有一个b,那显然这就是整个式子的最大值了(注意这个地方是基于题目中给的每个数字的范围都是2-1000,也就是不会有小数,也就不存在“越乘越大”“越除越小”的情况了,所以说这个条件让题目变简单了),这样的话,我们就可以总在式子的这个地方添加括号:
a/(b/c/d…) = a/b*(c/d…)

java的代码如下:

public class Solution {
  public String optimalDivision(int[] nums) {
        String str1 = "";
        if(nums.length==0)
        	return str1;
        else if(nums.length == 1)
        	return str1+nums[0];
        else if(nums.length ==2)
        	return str1 + nums[0] + "/" +nums[1];
        else {
        	str1 += nums[0] + "/(";
             for(int i=1;i<nums.length-1;i++)
            	 str1 += nums[i]+"/";
             str1 += nums[nums.length-1]+")";
             return str1;
        }
    }
  
	 
	public static void main(String[] args) {
      Solution solution =new Solution();
      int[] nums = {1};
	  System.out.print( solution.optimalDivision(nums));
	}
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/116855.html

(0)
seven_的头像seven_bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!