343. Integer Break

来源:互联网 发布:centos 无法打开https 编辑:程序博客网 时间:2024/06/15 17:26
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.
  • 这题的关键是递归公式dp[i] = max(dp[i-j]*j,(i-j)*j,dp[i]);
class Solution {public:    int integerBreak(int n) {        vector<int> dp(n+1,1);        if(n <= 1){            return 0;        }        dp[1] = 1;        dp[2] = 1;        for(int i = 3;i <= n;++i){            for(int j = 2; j < i;++j){                dp[i] = max(j*(i-j),dp[i]);                dp[i] = max(j*dp[i-j],dp[i]);            }            cout<<dp[i]<<endl;        }        return dp[n];    }};
原创粉丝点击