-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathUnique_BST.java
36 lines (32 loc) · 926 Bytes
/
Unique_BST.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Unique BSTs using DP
// For given n, how many structurally unique BST's that store values 1 ... n?
import java.io.*;
import java.util.*;
class Unique_BST {
// function will return no. of unique bsts
static int uniqueBST(int n) {
int count[] = new int[n + 1];
// for each 'i' number of nodes
for (int i = 1; i <= n; ++i) {
for (int j = 0; j < i; ++j) {
// No. of trees if j is a root
count[i] += Math.max(count[j], 1) * Math.max(count[i - j - 1], 1);
}
}
return count[n];
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number:");
int num = sc.nextInt();
System.out.println("Number of Unique BSTs " + uniqueBST(num));
}
}
/*
Input:
Enter the number:
3
Output:
Number of Unique BSTs 5
Time complexity : O(n)
*/