Leetcode553 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.


中文大意

給定一個數組,然後相鄰元素之間做除法操作“/”,可以通過加入括號,改變計算的優先級,使整個除法運算的結果最大,並將對應的除法表達式以字符串形式輸出。

分析:

(1)假設給的數組爲[X1,X2,X3,....,Xn],當加入括號的時候,由於優先級的改變,以及除法的性質(除以一個數,相當於乘以該數的倒數),所以一些元素是可以變形到分子上的。但是很顯然的是,無論我們如何添加括號,X1只能在分子的位置上,而X2只能在分母的位置上,那麼可以有:X1/X2/X3/.../Xn=(X1/X2)*Y,爲了保證最後得到的結果是最大的,那麼就可以使Y最大就可以。而乘法和除法之間是存在倒數的關係,所以Y最大的情況就是Y=X3*X4*X5*...*Xn,此時加入的括號爲:X1/(X2/X3/X4/X5/.../Xn)。從另外一個角度來看,我們也可以這樣理解:在保證分子X1不變的情況下,爲了使最後的結果最大,只能使分母最小,而使分母最小的方法就是X2作爲被除數,被X3、X4、...Xn連除,即X1/(X2/X3/X4/X5/.../Xn)。補充說明一下:在note中給出的一個條件是“數組中所有的元素都是大於1的",這樣也就保證了Y=X3*X4*...*Xn,隨着乘數的增加,Y是越來越大的。

(2)從技巧上,我們掌握了問題的解決方法,在我們編程實現的時候,只需要分情況考慮就可以了。由於note中給出了所給數組的最小長度爲1,那麼我們可以分三種情況:

a.當輸入的數組只有一個元素時;

b.當輸入的數組中只有兩個元素時;

c.當輸入的數組中的元素個數多於兩個時。

(3)注意,最後輸出的結果是對應表達式的字符串形式,而數組中的元素是int類型,那麼就會存在一個int類型和String之間相互轉換的問題,現在在這裏補充一下這一塊知識。

int-->Stirng 有兩種方式:

a.Sring s = "";  s + = i;

b.s = String.valueOf(i);

兩種方法的區別是:第一種方法會生成兩個字符串,因爲String類變量是不能改變長度的;第二種方法只會生成一個字符串。

String-->int有兩種方式:

a.i = Integer.valueOf(s).intValue();

b.i = Integer.parseInt(s);

兩種方法的區別是:第一種方法中,會多生成一個對象,Integer.valueOf(s)相當於new Integer(Integer.parseInt(s)),同時會拋出異常;第二種方法中,不會生成多餘的對象,但同時也會拋出異常的。


java代碼實現

class Solution {
    public String optimalDivision(int[] nums) {
        String res = "";
        res = res + nums[0];
        if(nums.length == 1){
            return res;
        }else if(nums.length == 2){
            return res = res + "/" + nums[1];
        }else{
            res = res + "/"+"("+nums[1];
            for(int i = 2; i < nums.length;i++){
                res = res + "/" +nums[i];
            }
            
            res = res + ")";
        }
        
        return res;
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章