1569. Number of Ways to Reorder Array to Get Same BST Hard
#Array#Math#Divide and Conquer#Dynamic Programming#Tree#Union Find#Binary Search Tree#Memoization#Combinatorics#Binary Tree
1/**
2 * [1569] Number of Ways to Reorder Array to Get Same BST
3 *
4 * 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.
5 *
6 * 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.
7 *
8 * Return the number of ways to reorder nums such that the BST formed is identical to the original BST formed from nums.
9 * Since the answer may be very large, return it modulo 10^9 + 7.
10 *
11 * Example 1:
12 * <img alt="" src="https://assets.leetcode.com/uploads/2020/08/12/bb.png" style="width: 121px; height: 101px;" />
13 * Input: nums = [2,1,3]
14 * Output: 1
15 * Explanation: We can reorder nums to be [2,3,1] which will yield the same BST. There are no other ways to reorder nums which will yield the same BST.
16 *
17 * Example 2:
18 * <img alt="" src="https://assets.leetcode.com/uploads/2020/08/12/ex1.png" style="width: 241px; height: 161px;" />
19 * Input: nums = [3,4,5,1,2]
20 * Output: 5
21 * Explanation: The following 5 arrays will yield the same BST:
22 * [3,1,2,4,5]
23 * [3,1,4,2,5]
24 * [3,1,4,5,2]
25 * [3,4,1,2,5]
26 * [3,4,1,5,2]
27 *
28 * Example 3:
29 * <img alt="" src="https://assets.leetcode.com/uploads/2020/08/12/ex4.png" style="width: 121px; height: 161px;" />
30 * Input: nums = [1,2,3]
31 * Output: 0
32 * Explanation: There are no other orderings of nums that will yield the same BST.
33 *
34 *
35 * Constraints:
36 *
37 * 1 <= nums.length <= 1000
38 * 1 <= nums[i] <= nums.length
39 * All integers in nums are distinct.
40 *
41 */
42pub struct Solution {}
43
44// problem: https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst/
45// discuss: https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst/discuss/?currentPage=1&orderBy=most_votes&query=
46
47// submission codes start here
48
49impl Solution {
50 pub fn num_of_ways(nums: Vec<i32>) -> i32 {
51 0
52 }
53}
54
55// submission codes end
56
57#[cfg(test)]
58mod tests {
59 use super::*;
60
61 #[test]
62 fn test_1569() {
63 }
64}
65
Back
© 2025 bowen.ge All Rights Reserved.