0
点赞
收藏
分享

微信扫一扫

Springboot_文件下载功能(前端后端)

Silence潇湘夜雨 2023-11-23 阅读 57
算法

343. Integer Break

Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers.

Return the maximum product you can get.

Greedy: 

1.  Break a number n into m positive integers,  an At least m-1 intergers are the same , to get the maximum product.    Interger cannot be 1, apparently.

2. Mathematical conclusions: if n > 3 ,  we need to make more interger 3  in those intergers so we can get the maximum product.  (2*2*2 < 3*3 .  4*4*4 < 3*3*3*3  No need to mention 5,6,7.....)

Time complexity: O(n)
Space complexity: O(1)

class Solution:
    def integerBreak(self, n: int) -> int:
        result = 1     
        if n == 2: return 1
        if n == 3: return 2
        if n == 4: return 4
        while n > 4: # 3*3*4
            result *= 3
            n -= 3
    
        return result * n

dp:

Time complexity: O(n^2)
Space complexity: O(n)

class Solution:
         # 假设对正整数 i 拆分出的第一个正整数是 j(1 <= j < i),则有以下两种方案:
        # 1) 将 i 拆分成 j 和 i−j 的和,且 i−j 不再拆分成多个正整数,此时的乘积是 j * (i-j)
        # 2) 将 i 拆分成 j 和 i−j 的和,且 i−j 继续拆分成多个正整数,此时的乘积是 j * dp[i-j]
    def integerBreak(self, n):
        dp = [0] * (n + 1)   # 创建一个大小为n+1的数组来存储计算结果
        dp[2] = 1  # 初始化dp[2]为1,因为当n=2时,只有一个切割方式1+1=2,乘积为1
       
        # 从3开始计算,直到n
        for i in range(3, n + 1):
            # 遍历所有可能的切割点
            for j in range(1, i // 2 + 1): #j是每次拆出来多少

                # 计算切割点j和剩余部分(i-j)的乘积,并与之前的结果进行比较取较大值
                
                dp[i] = max(dp[i], (i - j) * j, dp[i - j] * j)
        #j * (i - j) 是单纯的把整数 i 拆分为两个数 也就是 i,i-j ,再相乘
        #j * dp[i - j]还要将i-j这部分拆分成两个以及两个以上的个数, 再相乘
     
        return dp[n]  # 返回最终的计算结果

96. Unique Binary Search Trees

Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.

 

The number of search trees with 2 elements is dp[2].

The number of search trees with 1 element is dp[1].

The number of search trees with 0 elements is dp[0].

 

 Time complexity: O(n^2)

Space complexity: O(n)

AC:

class Solution:
    def numTrees(self, n: int) -> int:
        if n == 1: return 1

        dp = [0] * (n + 1)
        dp[0] = 1
        dp[1] = 1
        dp[2] = 2
        
        for i in range(3, n + 1):
            for j in range(1, i + 1):
                dp[i] += dp[i - j] * dp[j - 1]
        
        return dp[n]

optimal solution:

class Solution:
    def numTrees(self, n: int) -> int:
        dp = [0] * (n + 1)  # 创建一个长度为n+1的数组,初始化为0
        dp[0] = 1  # 当n为0时,只有一种情况,即空树,所以dp[0] = 1
        for i in range(1, n + 1):  # 遍历从1到n的每个数字
            for j in range(1, i + 1):  # 对于每个数字i,计算以i为根节点的二叉搜索树的数量
                dp[i] += dp[j - 1] * dp[i - j]  # 利用动态规划的思想,累加左子树和右子树的组合数量
        return dp[n]  # 返回以1到n为节点的二叉搜索树的总数量
举报

相关推荐

0 条评论