LeetCode 1569: Number of Ways to Reorder Array to Get Same BST
LeetCode 1569 Solution Explanation
Explanation:
This problem can be solved using dynamic programming. We can calculate the number of ways to reorder the array to get the same BST by considering each element as the root of the BST and recursively calculating the number of ways for the left and right subtrees.
- Define a recursive function that takes the array of integers and calculates the number of ways to reorder the array to get the same BST.
- For each element in the array, consider it as the root of the BST.
- Divide the array into left and right subtrees based on the current root element.
- Recursively calculate the number of ways for the left and right subtrees.
- Multiply the number of ways for the left and right subtrees to get the total number of ways for the current root element.
- Add the current root's number of ways to the total count.
- Return the total count modulo 10^9 + 7.
Time Complexity: O(n^2) Space Complexity: O(n)
:
LeetCode 1569 Solutions in Java, C++, Python
class Solution {
public int numOfWays(int[] nums) {
return (int) (dfs(nums) - 1) % 1000000007;
}
private long dfs(int[] nums) {
if (nums.length <= 1) {
return 1;
}
List<Integer> left = new ArrayList<>();
List<Integer> right = new ArrayList<>();
for (int i = 1; i < nums.length; i++) {
if (nums[i] < nums[0]) {
left.add(nums[i]);
} else {
right.add(nums[i]);
}
}
long leftWays = dfs(left.stream().mapToInt(i -> i).toArray());
long rightWays = dfs(right.stream().mapToInt(i -> i).toArray());
return (factorial(left.size() + right.size()) / (factorial(left.size()) * factorial(right.size()))) * leftWays * rightWays;
}
private long factorial(int n) {
long result = 1;
for (int i = 1; i <= n; i++) {
result = (result * i) % 1000000007;
}
return result;
}
}
Interactive Code Editor for LeetCode 1569
Improve Your LeetCode 1569 Solution
Use the editor below to refine the provided solution for LeetCode 1569. Select a programming language and try the following:
- Add import statements if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.
Loading editor...