553. Optimal Division 数学、字符串

来源:互联网 发布:下淘宝网手机版 编辑:程序博客网 时间:2024/06/06 14:19

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) = 200However, 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 = 501000/(100/(10/2)) = 501000/100/10/2 = 0.51000/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].

  1. 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
把第二个数到最后括起来一定是最大值,因为这样可以将第三个数开始的除号变成乘号
class Solution {public:    string optimalDivision(vector<int>& nums) {        string res;        if(nums.empty()) return res;        res=to_string(nums[0]);        if(nums.size()==1) return res;        if(nums.size()==2) return res+"/"+to_string(nums[1]);        res+="/("+to_string(nums[1]);        for(int i=2;i<nums.size();i++)        {            res+="/"+to_string(nums[i]);        }        res+=")";        return res;            }};


原创粉丝点击