553. Optimal Division(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/84202001

题目:

Given a list of positive integers, the adjacent integers will performthe 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 containredundant 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.

解释:
在任何位置加括号来改变算数的优先级,以得到最大的结果,最终的式子以字符串的形式给出~
这道题非常tricky,我们注意到除了第一个除数之外,后面的数都可以转变为乘积!!!
拿样例来说:
1000/(100/10/2) == (1000102)/(100)
所以,我们只需要考虑三种情况:
1.只有一个数,直接返回;
2.有两个数,第一个除以第二个返回;
3.有三个及以上的数,把第二个数后面的所有数和第一个数全部乘起来,最后除以第二个数,成起来的表现就是直接连除,最外层用括号包起来。(因为note当中说明了,给的数字都是[2,1000]的,所以第二个数后面的所有数乘起来都只会让结果变大)。
python代码:

class Solution(object):
    def optimalDivision(self, nums):
        """
        :type nums: List[int]
        :rtype: str
        """
        len_nums=len(nums)
        if len_nums==1:
            return str(nums[0])
        elif len_nums==2:
            return '%s/%s'%(str(nums[0]),str(nums[1]))
        else:
            return '%s/%s'%(str(nums[0]),'(%s)'%'/'.join([str(i) for i in nums[1:]]))

c++代码:

class Solution {
public:
    string optimalDivision(vector<int>& nums) {
        int len_nums=nums.size();
        if (len_nums==1)
            return to_string(nums[0]);
        else if (len_nums==2)
            return to_string(nums[0])+"/"+to_string(nums[1]);
        else
        {
            string result=to_string(nums[0])+"/(";
            for (int i=1;i<len_nums;i++)
            {
                result+=to_string(nums[i]);
                if (i!=len_nums-1)
                    result+="/";
            }
            result+=")";
             return result;
        }
    }
};

总结:

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/84202001