[LeetCode] 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:

  1. The length of the input array is [1, 10].
  2. Elements in the given array will be in range [2, 1000].
  3. There is only one optimal division for each test case.

 

這道題給了我們一個數組,讓我們確定除法的順序,從而得到值最大的運算順序,並且不能加多余的括號。剛開始博主沒看清題,以為是要返回最大的值,就直接寫了個遞歸的暴力搜索的方法,結果發現是要返回帶括號的字符串,嘗試的修改了一下,覺得挺麻煩。於是直接放棄抵抗,上網參考大神們的解法,結果大吃一驚,這題原來還可以這么解,完全是數學上的知識啊,太tricky了。數組中n個數字,如果不加括號就是:

x1 / x2 / x3 / ... / xn

那么我們如何加括號使得其值最大呢,那么就是將x2后面的除數都變成乘數,比如只有三個數字的情況 a / b / c,如果我們在后兩個數上加上括號 a / (b / c),實際上就是a / b * c。而且b永遠只能當除數,a也永遠只能當被除數。同理,x1只能當被除數,x2只能當除數,但是x3之后的數,只要我們都將其變為乘數,那么得到的值肯定是最大的,所以就只有一種加括號的方式,即:

x1 / (x2 / x3 / ... / xn)

這樣的話就完全不用遞歸了,這道題就變成了一個道簡單的字符串操作的題目了,這思路,博主服了,參見代碼如下:

 

解法一:

class Solution {
public:
    string optimalDivision(vector<int>& nums) {
        if (nums.empty()) return "";
        string 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]);
        }
        return res + ")";
    }
};

 

下面這種解法的思路和上面基本相同,就是寫法上略有不同,直接看代碼吧:

 

解法二:

class Solution {
public:
    string optimalDivision(vector<int>& nums) {
        string res = "";
        int n = nums.size();
        for (int i = 0; i < n; ++i) {
            if (i > 0) res += "/";
            if (i == 1 && n > 2) res += "(";
            res += to_string(nums[i]);
            if (i == n - 1 && n > 2) res += ")";
        }
        return res;
    }
};

 

參考資料:

https://discuss.leetcode.com/topic/86487/c-java-clean-code

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

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM