[LeetCode]Optimal Division

题目描述:

LeetCode 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) = 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:

  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,3,4] -> 2 / 3 / 4

在其中加入括号可以改变运算顺序,求运算结果最大时的加括号方案,返回表达式。

注意:

  1. 输入整数长度范围[1, 10]
  2. 元素范围[2, 1000]
  3. 输入确保有唯一解

解题思路:

解法I 数学

在不添加任何括号的情况下:

a / b / c / d / ... = a / (b * c * d * ...)

在算式中添加括号会使得被除数和除数的构成发生变化

但无论括号的位置如何,a一定是被除数的一部分,b一定是除数的一部分

原式添加括号方案的最大值,等价于求除数的最小值

因此最优添加括号方案为:

a / (b / c / d / ...) = a * c * d * ... / b

Python代码:

class Solution(object):
    def optimalDivision(self, nums):
        """
        :type nums: List[int]
        :rtype: str
        """
        nums = map(str, nums)
        return len(nums) < 3 and '/'.join(nums) or nums[0] + '/(' + '/'.join(nums[1:]) + ')'

解法II 穷举法

递归枚举分割点,将nums分成左右两半

当右半部分的长度大于1时,为右半部分加括号

Python代码:

class Solution(object):
    def optimalDivision(self, nums):
        """
        :type nums: List[int]
        :rtype: str
        """
        def solve(snums):
            if len(snums) == 1: yield snums[0]
            for x in range(1, len(snums)):
                left, right = snums[:x], snums[x:]
                l = '/'.join(left)
                if len(right) == 1:
                    yield l + '/' + right[0]
                else:
                    for r in solve(right):
                        yield l + '/(' + r + ')'
        ans, best = '', 0
        for expr in solve(map(str, nums)):
            val = eval(expr.replace('/', '.0/'))
            if val > best: ans, best = expr, val
        return ans

 

本文链接:http://bookshadow.com/weblog/2017/04/16/leetcode-optimal-division/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论