给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。
示例 1:
输入: 2
输出: 1
解释: 2 = 1 + 1, 1 × 1 = 1。
示例 2:
输入: 10
输出: 36
解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。
说明: 你可以假设 n 不小于 2 且不大于 58。
class Solution {//N^2
public:
int integerBreak(int n) {
if(n==2)return 1;
if(n==3)return 2;
vector<int> dp(n+1,0);
dp[1]=1;
dp[2]=2;
dp[3]=3;
for(int i=4;i<=n;++i){
for(int j=1;j<=(i>>1);++j){
dp[i]=max(dp[i],dp[j]*dp[i-j]);
}
}
return dp[n];
}
};
class Solution {//O(N)
public:
int integerBreak(int n) {//f(n)=2^x+3^y
if(n==2)return 1;
if(n==3)return 2;
vector<int> dp(n+1,0);
dp[1]=1;
dp[2]=2;
dp[3]=3;
for(int i=4;i<=n;++i)
dp[i]=max(2*dp[i-2],3*dp[i-3]);
return dp[n];
}
};
//改进
class Solution {
public:
int integerBreak(int n) {//f(n)=2^x+3^y
if(n==2)return 1;
if(n==3)return 2;
int dp1=1,dp2=2,dp3=3,dp4,temp;
for(int i=4;i<=n;++i){
temp=dp4;
dp4=max(2*dp2,3*dp1);
dp1=dp2,dp2=dp3,dp3=dp4;
}
return dp4;
}
};
class Solution {//O(1) 3尽可能的多,配上0个2或者一个2或者一个4
public:
int integerBreak(int n) {//f(n)=2^x+3^y
if(n==2)return 1;
if(n==3)return 2;
int a=n/3,b=n%3;
if(b==0)return pow(3,a);
else if(b=&#