给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。
示例 1:
输入: 2
输出: 1
解释: 2 = 1 + 1, 1 × 1 = 1。
示例 2:
输入: 10
输出: 36
解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。
说明: 你可以假设 n 不小于 2 且不大于 58。
? https://leetcode-cn.com/problems/integer-break
暴力枚举所有的情况
class Solution {
public:
int maxx = 0;
vector path;
void f(int i,int j){ // i 是每次能减去的步数集合 j是还剩余的步长
if (i == 1 || j == 0) {
int s = 1;
for (auto t:path) s *= t;
maxx = max(maxx,s);
return;
}
for (int u = 1; u <= i; ++u){
if (j - u >= 0){
path.push_back(u);
f(u,j-u);
auto it = path.end();
it--;
path.erase(it);
}
}
}
int integerBreak(int n) {
if (n == 2) return 1;
if (n == 3) return 2;
f(n,n);
return maxx;
}
};
动态规划
class Solution {
public:
int dp[60];
void init(){
dp[1] = 1;
dp[2] = 2;
dp[3] = 3;
dp[4] = 4;
for(int i = 5;i<=58;++i){
for(int j = 1;j