Leetcode_343 整数拆分

题目描述

Leetcode_343 整数拆分_第1张图片

解题思路

c++

#include 
#include 
using namespace std;

class Solution {
private:
    vector<int> memo;

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

    int getMax(int n)
    {
        if(n == 1)
        {
            return 1;
        }
        if(memo[n]!=-1)
            return memo[n];
        int res = -1;
        for(int i =1;ireturn res;
    }
public:
    int integerBreak(int n) {
        memo = vector<int>(n+1,-1);
        return getMax(n);        
    }
};


int main()
{
    cout<38)<return 0;
}
#include 
#include 
using namespace std;

class Solution {
private:
    vector<int> memo;

    int max3(int a, int b, int c)
    {
        return max(a,max(b,c));
    }
public:
    int integerBreak(int n) {
        vector<int> memo(n+1,-1);
        memo[1] = 1;
        for(int i = 2; i<=n; i++)
            for(int j = 1;j<=i-1;j++)
                memo[i] = max3(memo[i],j*(i-j),j*memo[i-j]);

        return memo[n];

    }

};

int main()
{
    cout<38)<return 0;
}

java

class Solution {
    public int integerBreak(int n) {
        int [] dp = new int[n];
        dp[1] = 1;
        for(int i = 2;i<=n;i++)
        {
            for(int j = 1;j<=i-1;j++)
            {
                dp[i]= Math.max(dp[i],Math.max(j*(i-j),j*dp[i-j]));
            }
        }
        return dp[n];

    }
}

你可能感兴趣的:(leetcode,编码,Leetcode)