Leetcode-343_Integer Break(整数分解) -动态规划解法-Leetcode大神解法-【C++】

Leetcode-343Integer Break(整数分解)

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.

首先分析一下这道题,是要将一个整数分解成其他整数和,使得其乘积最大,比如说10,可以分解为3+3+4,334=36是10可以分解的最大的一个解,10也可以分解为2+2+2+4,但是222*4=32比36小,所以这不是我们要的解。

整体看起来这道题也是属于典型的动态规划的题型,所以我接下来就不用递归求解它了,直接使用动态规划求解相对比较好下手。

我在Leetcode提交的代码

class Solution {
public:
    int integerBreak(int n) {
        vector memo=vector(n+2,-1);
        memo[1] = 1;
        memo[2] = 1;
        memo[3] = 2;
        for (int i=2 ;i<=n;i++)
        {
            for(int j=1;j

Leetcode上大神的解法

class Solution {
public:
    int integerBreak(int n) {
        // DP
        // dp[i] = max product of int i
        // to get dp[i], find the highest dp[j] * (i - j) from 0 to i;
        
        vector dp(n + 1, 1);
        for (int i = 3; i < dp.size(); i++) {
            for (int j = 2; j < i; j++) {
                if (dp[j] * (i - j) > dp[i])
                    dp[i] = dp[j] * (i - j);
                if (j * (i - j) > dp[i])
                    dp[i] = j * (i - j);
            }
        }
        
        return dp[n];
    }
};

自己可以调试的代码

#include 
#include 
using namespace std;

int main(int argc, char *argv[]) {
	int n = 10;
	vector memo=vector(n+2,-1);
	memo[1] = 1;
	memo[2] = 1;
	memo[3] = 2;
	for (int i=2 ;i<=n;i++)
	{
		for(int j=1;j

运行结果2ms

Leetcode-343_Integer Break(整数分解) -动态规划解法-Leetcode大神解法-【C++】_第1张图片

你可能感兴趣的:(【Leetcode题解】,算法学习及Leetcode题解)