Leetcode343

Integer 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.
Example 1:
Input: 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example 2:
Input: 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
Note: You may assume that n is not less than 2 and not larger than 58.

Solution: 自顶向下(记忆化搜索)

#include <iostream>
#include <vector>

using namespace std;

class Solution {
private:

    vector<int> memo;

    int max3(int a, int b, int c){
        return max(a, max(b, c));
    }

    // 将n进行分割(至少分割两部分),可以获得的最大乘积
    int breakInteger( int n ){

        if ( n == 1 )
            return 1;

        int res = -1;

        if ( memo[n] != -1 )
            return memo[n];

        for ( int i = 1; i <= n-1; i++ )
            // i + (n-i)
           res = max3( res, i * (n-i), i * breakInteger(n-i));

        memo[n] = res;
        return res;
    }
public:
    int integerBreak(int n) {

        memo = vector<int> (n+1, -1);

        return breakInteger(n);

    }
};

Solution:自底向上(动态规划)

#include <iostream>
#include <vector>

using namespace std;

class Solution {
private:

    int max3(int a, int b, int c){
        return max(a, max(b, c));
    }

public:
    int integerBreak(int n) {

        // memo[i]表示将数字i分割(至少分割成两部分)后得到的最大乘积
        vector<int> memo(n+1, -1);

        memo[1] = 1;
        for (int i = 2; i <= n; i++) {
            // 求解memo[i]
            for (int j = 1; j <= i-1; j++) {
                // j + (i-j)
                memo[i] = max3( memo[i], j * (i-j), j * memo[i-j]);
            }
        }

        return memo[n];

    }
};

总结:
分析问题:
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值