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

  • 相关阅读:
    埋点功能测试
    jmeter提取A接口返回值传入B接口
    css(2)---倒角阴影 框模型
    css(1)
    node 练习
    学习过程中遇到的问题及解决方法
    node.js(5)——mysql、连接池
    node.js(4)——中间件
    node.js(3)——express
    node.js(2)
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6807513.html
Copyright © 2011-2022 走看看