算法作业_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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值