动归 递归拆
- class Solution:
- def integerBreak(self, n: int) -> int:
- dp=[0]*(n+1)
- dp[2]=1
- for i in range(3,n+1):
- for j in range(1,i//2+1):
- dp[i]=max(dp[i],(i-j)*j,dp[i-j]*j)
- return dp[n]
公式:全拆3,剩1个4
- class Solution:
- def integerBreak(self, n: int) -> int:
- if n==1:return 1
- if n==2:return 1
- if n==3:return 2
- return pow(3,int(n//3)-1)*4
究极拆分 左排列*右排列
- class Solution:
- def numTrees(self, n: int) -> int:
- dp=[0]*(n+1)
- dp[0]=1
- for i in range(1,n+1):
- for j in range(1,i+1):
- dp[i]+=dp[j-1]*dp[i-j]
- return dp[n]