343. 整数拆分

链接:https://leetcode-cn.com/problems/integer-break/submissions/

题解:https://leetcode-cn.com/problems/integer-break/solution/shou-hua-tu-jie-di-gui-ji-yi-hua-di-gui-dong-tai-g/

mem[n]表示,拆分n的最大值

image.png

class Solution {
public:
    int integerBreak(int n) {
        // 记忆化
        vector<long> memo(n+1, INT_MIN);
        dfs(n, memo);
        return memo[n];
    }
    long dfs(long n, vector<long>& memo) {
        // 
        if(memo[n] != INT_MIN) {
            return memo[n];
        }
        long temp = INT_MIN;
        // max(i*(n-i), i*dfs(n-i, memo))
        for(int i = 1; i < n; ++i) {
            long max_value = i*(n-i);
            long value2 = i*dfs(n-i, memo);
            if(max_value < value2) {
                max_value = value2;
            }
            if(max_value > temp) {
                temp = max_value;
            }
        }
        memo[n] = temp;
        return temp;
    }
};

 

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页