Approach
Depth-first search
For Number of Ways to Reorder Array to Get Same Bst, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 64 lines of Python from the credited upstream file number-of-ways-to-reorder-array-to-get-same-bst.py.
- The implementation visibly relies on sequence storage, cached states.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4MAX_N = 10005MOD = 10**9+76dp = [[0]*MAX_N for _ in xrange(MAX_N)]7for i in xrange(len(dp)):8 dp[i][0] = 19 for j in xrange(1, i+1):10 dp[i][j] = (dp[i-1][j-1] + dp[i-1][j])%MOD11 12 13class Solution(object):14 def numOfWays(self, nums):15 """16 :type nums: List[int]17 :rtype: int18 """19 def iter_dfs(nums):20 result = [0]21 stk = [[1, [nums, result]]]22 while stk:23 step, params = stk.pop()24 if step == 1:25 nums, ret = params26 if len(nums) <= 2:27 ret[0] = 128 continue29 left = [v for v in nums if v < nums[0]]30 right = [v for v in nums if v > nums[0]]31 ret[0] = dp[len(left)+len(right)][len(left)]32 ret1, ret2 = [0], [0]33 stk.append([2, [ret1, ret2, ret]])34 stk.append([1, [right, ret2]])35 stk.append([1, [left, ret1]])36 elif step == 2:37 ret1, ret2, ret = params38 ret[0] = ret[0]*ret1[0] % MOD39 ret[0] = ret[0]*ret2[0] % MOD40 return result[0]41 42 return (iter_dfs(nums)-1)%MOD43 44 454647class Solution(object):48 def numOfWays(self, nums):49 """50 :type nums: List[int]51 :rtype: int52 """53 def dfs(nums):54 if len(nums) <= 2:55 return 156 left = [v for v in nums if v < nums[0]]57 right = [v for v in nums if v > nums[0]]58 result = dp[len(left)+len(right)][len(left)]59 result = result*dfs(left) % MOD60 result = result*dfs(right) % MOD61 return result62 63 return (dfs(nums)-1)%MOD64