leetcode 343. 整数拆分(动态规划)

思路来源:https://leetcode-cn.com/problems/integer-break/solution/pythondp-tong-su-yi-dong-an-zhao-zi-ji-de-bu-fa-la/
https://leetcode-cn.com/problems/integer-break/solution/bao-li-sou-suo-ji-yi-hua-sou-suo-dong-tai-gui-hua-/

python代码:

class Solution(object):
    def integerBreak(self, n):
        """
        :type n: int
        :rtype: int
        """
        mem = [-float("inf")] * (n + 1)
        return self.dynamicProgram(n, mem)
    """ 
    #自顶向下
    def memRecursion(self, n, mem):
        if n == 2:
            return 1
        if mem[n] > 0:
            return mem[n]
        res = -float("inf")
        for i in range(2, n):
            res = max(res, max(i * self.integerBreak(n - i), i * (n - i)))
        mem[n] = res
        return res
    """ 
    #自底向上   
    def dynamicProgram(self, n, mem):
        mem[2] = 1
        res = -float("inf")
        for i in range(2, n + 1):
            for j in range(1, i + 1):
                #print(i, j, j * (i - j), j * mem[i - j], res)
                res = max(j * (i - j), j * mem[i - j], res)
            mem[i] = res
        return res

x = Solution()
t = x.integerBreak(2)
print(t)

你可能感兴趣的:(leetcode)