leetcode 553. Optimal divider (Optimal Division)

Subject description:

Given a set of positive integers , floating point division operation will be performed between adjacent integers. For example, [2,3,4] -> 2/3/4.

However, you can add any number of brackets in any position to change the priority of arithmetic. You need to find out how to add brackets, in order to get maximum results and returns the corresponding string expression format. Your expression should not contain redundant parentheses .

Example:

输入: [1000,100,10,2]
输出: "1000/(100/10/2)"
解释:
    1000/(100/10/2) = 1000/((100/10)/2) = 200
    但是,以下加粗的括号 "1000/((100/10)/2)" 是冗余的,
    因为他们并不影响操作的优先级,所以你需要返回 "1000/(100/10/2)"。

其他用例:
    1000/(100/10)/2 = 50
    1000/(100/(10/2)) = 50
    1000/100/10/2 = 0.5
    1000/100/(10/2) = 2

Description:

  • Between the length of the input array [1, 10].
  • The size of each array element are between [2, 1000].
  • Each test case is only one optimal solution division.

solution:

class Solution {
public:
    string itoa(int num){
        string res = "";
        // assert(num > 0);
        while(num > 0){
            res = char(num%10 + '0') + res;
            num /= 10;
        }
        return res;
    }
    
    string optimalDivision(vector<int>& nums) {
        string res = "";
        int sz = nums.size();
        if(sz == 1){
            res = itoa(nums[0]);
        }else if(sz == 2){
            res = itoa(nums[0]) + "/" + itoa(nums[1]);
        }else{
            res = itoa(nums[0]) + "/(";
            for(int i = 1; i < sz-1; i++){
                res += itoa(nums[i]) + "/";
            }
            res += itoa(nums[sz-1]) + ")";
        }
        return res;
    }
};

Guess you like

Origin www.cnblogs.com/zhanzq/p/10953632.html