解難題Leetcode 1569 Number of Ways to Reorder Array to Get Same BST
Python/C++使用組合數學解決問題之方法:重新排列陣列獲得相同二元搜尋樹的方法數(內含python code)
首先,陣列的第一個元素必須成為樹的根節點。
接著將陣列分成左子樹和右子樹。
利用遞迴,如果左子樹和右子樹的子問題已經解決,分別返回數字 l 和 r,則可以使用以下公式解決問題:
總方法數 = l * r * C_左子樹長度^(N-1) -1
請記得要對計算結果進行模 10**9+7 的運算。
- class Solution:
- def numOfWays(self, nums: List[int]) -> int:
- Mod=10**9+7
- import math
- def Subproblem(nums: List[int]):
- n=len(nums)
- if n<=2: return 1
- root=nums[0]
- left=[]
- right=[]
- for y in nums[1:]:
- if y<root: left.append(y)
- else: right.append(y)
- return Subproblem(right)*Subproblem(left)%Mod*math.comb(len(nums)-1, len(left))%Mod
- return int((Subproblem(nums)-1)%Mod)
沒有留言:
張貼留言