[LeetCode] Number of Ways to Reorder Array to Get Same BST

1569. Number of Ways to Reorder Array to Get Same BST

Given an array nums that represents a permutation of integers from 1 to n. We are going to construct a binary search tree (BST) by inserting the elements of nums in order into an initially empty BST. Find the number of different ways to reorder nums so that the constructed BST is identical to that formed from the original array nums.

  • For example, given nums = [2,1,3], we will have 2 as the root, 1 as a left child, and 3 as a right child. The array [2,3,1] also yields the same BST but [3,2,1] yields a different BST.

Return the number of ways to reorder nums such that the BST formed is identical to the original BST formed from nums.

Since the answer may be very large, return it modulo 109 + 7.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
int mod = 1e9 + 7;
int dp[1010][1010];
int comb(int n, int m) {
if(n == 0 or m == 0) return 1;
if(dp[n][m] != -1) return dp[n][m];
return dp[n][m] = (comb(n-1,m) + comb(n,m-1)) % mod;
}
int helper(vector<int>& A) {
if(A.size() <= 1) return 1;
vector<int> lower, higher;
copy_if(begin(A), end(A), back_inserter(lower), [&](int i) {return i < A.front();});
copy_if(begin(A), end(A), back_inserter(higher), [&](int i) {return i > A.front();});
return 1ll * helper(lower) * helper(higher) % mod * comb(lower.size(), higher.size()) % mod;
}
public:
int numOfWays(vector<int>& nums) {
memset(dp, -1, sizeof dp);
return helper(nums) - 1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/01/PS/LeetCode/number-of-ways-to-reorder-array-to-get-same-bst/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.