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

  • 相关阅读:
    04-基本的mysql语句
    03-MySql安装和基本管理
    02-数据库的概述
    MySql的前戏
    Python3连接MySQL数据库之pymysql模块的使用
    mockjs简单易懂
    GitHub Android 开源项目汇总 (转)
    国内云计算的缺失环节: GPU并行计算(转)
    HDFS+MapReduce+Hive+HBase十分钟快速入门
    同步和异步
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6807513.html
Copyright © 2011-2022 走看看