元模式

小白成长之路

343. Integer Break (动态规划)

1.Description

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.


2. Analysis

对于n来说,它可以被拆分为 n1n2的和,而 n1n2又可以被拆分为其他的和,最小一定是止于 n = 1,n = 2, n = 3这三者之中。(待我考完试再来仔细写明分析过程,其实很简单的)。时间复杂度为O(n2)

状态转移方程:

dp[i]=max(dp[ij]dp[j],(ij)j,dp[ij]j,(ij)dp[j],dp[i]);

3. Code

class Solution {
public:

    static int max(int a, int b, int c, int d, int origin) {
        int t1 = (a >= b)? a : b;
        int t2 = (c >= d)? c : d;
        int t3 =  (t1 >= t2) ? t1 : t2;
        return t3 >= origin ? t3 : origin;
    }


    int integerBreak(int n) {
        if(n == 2) return 1;
        if(n == 3) return 2;
        dp[1] = 1;
        dp[2] = 1;
        dp[3] = 2;
        for(int i = 4; i <= n; i++) {
            dp[i] = 0;
            //这里可以改进一下,因为不需要遍历到 i-1,拆分i的左右两边是对称的
            for(int j = 1; j < i; j++) 
                dp[i] = max(dp[i-j]*dp[j], (i-j)*j, dp[i-j]*j, (i-j)*dp[j], dp[i]);
        }
        return dp[n];
    }
private:
    int dp[60];
};
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/w_bu_neng_ku/article/details/78493932
文章标签: 动态规划
个人分类: LeetCode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭