leetcode-343-整数拆分

题目描述:

 

 方法一:数学 O(1) O(1)

class Solution:
    def integerBreak(self, n: int) -> int:
        if n <= 3: return n - 1
        a, b = n // 3, n % 3
        if b == 0: return int(math.pow(3, a))
        if b == 1: return int(math.pow(3, a - 1) * 4)
        return int(math.pow(3, a) * 2)

作者:jyd
链接:https://leetcode-cn.com/problems/integer-break/solution/343-zheng-shu-chai-fen-tan-xin-by-jyd/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

方法二:动态规划 O(n) O(n)

class Solution:
    def integerBreak(self, n: int) -> int:
        dp = [None, None, 1, 2, 4, 6, 9]
        if n < 7:
            return dp[n]
        for i in range(7, n+1):
            dp.append(dp[i-3]*3)
        return dp[-1]

 

posted @ 2020-08-01 09:27  oldby  阅读(105)  评论(0编辑  收藏  举报