算法作業_29(2017.6.12第十七週)

343. Integer Break

Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.

For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).

Note: You may assume that n is not less than 2 and not larger than 58.

解法一:遞歸的求解,n可以分解成: 1*(n-1),2*(n-2).......(n-1)*1。然後(n-1),(n-2),(n-3)...還可以繼續分割下去,可以遞歸的求出,但是提交時會報錯: Time Limit Exceeded:

class Solution {
public:
    int integerBreak(int n) {
        return breakInteger(n);
    }
    
    
private:
    int breakInteger(int n ){
        int res = -1;
        if(n==1)
            return 1;
        for(int i =1;i<=n-1;i++){
            res = max3(res,i*breakInteger(n-i),i*(n-i));
        }
        return res;
    }
    
private:
    int max3(int a ,int b ,int c){
        return max(a,max(b,c));
    }
};

解法二:記憶化搜索,上面的問題會導致內存溢出,是因爲有大量的重複計算,所以我們可以在遞歸的時候記錄已經計算過的值,並用數組存儲起來,這樣可以減少重複計算:AC

class Solution {
public:
    int integerBreak(int n) {
        memo = vector<int>(n+1,-1);
        return breakInteger(n);
    }
    
    
private:
    vector<int>memo;
    int breakInteger(int n ){
        if(n==1)
            return 1;
        if(memo[n]!=-1)
            return memo[n];
        
        int res = -1;
        for(int i =1;i<=n-1;i++){
            res = max3(res,i*breakInteger(n-i),i*(n-i));
        }
        memo[n] = res;
        return res;
    }
    int max3(int a ,int b ,int c){
        return max(a,max(b,c));
    }
};

解法三:動態規劃,將解法二進一步優化就是動態規劃的思想:

class Solution {
    public:
    int integerBreak(int n) {
        vector<int> dp(n+1,-1);
        //dp[i]表示把數字i分割(至少分成兩份)後的最大乘積
        dp[1]=1;
        for(int i =2;i<=n;i++){
            
            for(int j =1;j<=i-1;j++){
                dp[i] = max3(dp[i],j*dp[i-j],j*(i-j));
            }
        }
        return dp[n];
       
    }
    private:
    int max3(int a ,int b ,int c){
        return max(a,max(b,c));
    }



 

343. Integer Break

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