算法作业_29(2017.6.12第十七周)

来源:互联网 发布:linux解压tar包命令 编辑:程序博客网 时间:2024/06/11 05:34

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

原创粉丝点击