zoukankan      html  css  js  c++  java
  • (DP 暂时不会) leetcode 343. 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.

    ===============================================

    这个可以用DP,时间复杂度是O(n^2)。

    dp[i] = max(i],max(j,dp[j])*max(i-j,dp[i-j]));  这个状态转移式中,我认为,j + (i - j) = i,所以,能够表示可能的最大乘积为 i * ( i- j),不过可以用到之前的dp[j]和dp[i-j],因为,其中dp[j]可以是j的最大的分解结果,也可以是i的最大的分解结果。

    C++代码:

    class Solution {
    public:
        int integerBreak(int n) {
            vector<int> dp(n+1,0);
            dp[1] = dp[2] = 1;
            for(int i = 3; i <= n; i++){
                for(int j = 1; j <= i; j++){
                    dp[i] = max(dp[i],max(j,dp[j])*max(i-j,dp[i-j]));
                }
            }
            return dp[n];
        }
    };
  • 相关阅读:
    TS之类的继承
    TS之函数及函数传参
    TS之数据类型
    Linux 协程
    设计模式 装饰器模式和代理模式
    C/C++ C和C++的区别
    C/C++ 内存分配方式
    Linux 进程间通信
    C/C++ RTTI
    Reactor设计模式
  • 原文地址:https://www.cnblogs.com/Weixu-Liu/p/10864839.html
Copyright © 2011-2022 走看看