343 整数拆分

本文最后更新于:2022年4月9日 中午

给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。

示例 1:

1
2
3
输入: 2
输出: 1
解释: 2 = 1 + 1, 1 × 1 = 1。

示例 2:

1
2
3
输入: 10
输出: 36
解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。

说明: 你可以假设 n 不小于 2 且不大于 58。

Solution

参考 @liuyubobobo 、**@LeetCode官方**

  • 深度优先搜索,超时

image-20210130100926528

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// @lc code=start
class Solution {
private:
int dfs(int n){
if(n==1)
return n;

int res = -1;
for(int i=1; i<=n-1; ++i){
res = max(res, max(i*(n-i), i*dfs(n-i)));
}
return res;
}
public:
int integerBreak(int n) {
return dfs(n);
}
};
// @lc code=end
  • 记忆优化搜索,备忘录
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
private:
vector<int> memo;

int dfs(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 = max(res, max(i*(n-i), i*dfs(n-i)));
}
memo[n] = res;
return res;
}
public:
int integerBreak(int n) {
memo = vector<int>(n+1, -1);
return dfs(n);
}
};
  • 动态规划
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int integerBreak(int n) {
vector<int> dp(n+1, -1);
dp[1] = 1;
for(int i=2; i<=n; ++i){
for(int j=1; j<=i-1; ++j){
dp[i] = max(dp[i], max(j*(i-j), j*dp[i-j]));
}
}
return dp[n];
}
};

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!