您的位置:首页 > 其它

343. Integer Break

2017-09-01 09:37 429 查看
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.

题意:

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

例如,给定n = 2,返回1(2 = 1 + 1); 给定n = 10,返回36(10 = 3 + 3 + 4)。

注意:您可以假设n不小于2且不大于58。

直接使用找规律的方法:

int integerBreak(int n) {
if (n == 2) return 1;
if (n == 3) return 2;
if (n == 4) return 4;
int times = n / 3;
int more = n % 3;
int more_times = 1;
if (times > 1 && more == 1)//如果余数为1 ,加到3的上面,为2的话,就不加
{
times--;
more += 3;
}
cout << "more: " << more << "  more_times: " << more_times << "  times:" << times << endl;
return more == 0 ? pow(3, times) : pow(3, times)* pow(more, more_times);
}


别人的方法:

思路:

1. 一个整数等于两个子整数的和,积为子整数的乘积,选择最大的即可;

class Solution {
public:
int integerBreak(int n)
{
vector<int> dp(n+1,0);
dp[1] = 1;
for (int i = 2; i < dp.size();i++)
{
for (int j = 1; j < i /2 + 1;j++)
{
dp[i] = max(dp[i],max(dp[j],j)*max(i-j,dp[i-j]));
}
}
return dp
;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: