zoukankan      html  css  js  c++  java
  • [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:
    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.

    思路:

    大牛原话:

    “X1/X2/X3/../Xn will always be equal to (X1/X2) * Y,no matter how you place parentheses.

    i.e no matter how you place parentheses, X1 always goes to the numerator and X2 always goes to the denominator.

    Hence you just need to maximize Y. And Y is maximized when it is equal to X3 *..*Xn.

    So the answer is always X1/(X2/X3/../Xn) = (X1 *X3 *..*Xn)/X2

    有了这个结果其实就简单了。。。重要的是过程,要想得到最大结果,那么第一个数字X1一定是作为分子,第二个数X2一定是作为分母。

    于是就有了X1/(X2/X3/../Xn) 。

    string optimalDivision(vector<int>& nums)
         {
             string ret;
             ret = to_string(nums[0]);
             if (nums.size() == 1)return ret;
             if (nums.size() == 2) return ret + "/" + to_string(nums[1]);
             ret += "/(" + to_string(nums[1]);
             for (int i = 2; i < nums.size();i++)
             {
                 ret += "/" + to_string(nums[i]);
             }
             ret += ")";        
             return ret;
         }

    参考:

    https://discuss.leetcode.com/topic/86483/easy-to-understand-simple-o-n-solution-with-explanation/2

  • 相关阅读:
    断点续传的原理
    中国无线音乐搜索综合测评结果
    从头开始学jsp
    SQLServer和Oracle常用函数对比
    Asp.net程序重启自己
    What Can I do if "The type initializer for 'Emgu.CV.CvInvoke' threw an exception"?
    C++Builder2010多线程调用WebService的问题
    Desmon and Penny
    C#显示摄像头预览
    甲骨文78亿美金并购全球第二芯片商AMD
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6807513.html
Copyright © 2011-2022 走看看