Skip to content

Instantly share code, notes, and snippets.

@JyotinderSingh
Created June 24, 2020 14:37
Show Gist options
  • Save JyotinderSingh/bf5919b9c91630e863536d98b4a453de to your computer and use it in GitHub Desktop.
Save JyotinderSingh/bf5919b9c91630e863536d98b4a453de to your computer and use it in GitHub Desktop.
Unique Binary Search Trees (LeetCode) | Dynamic Programming
class Solution {
public:
int numTrees(int n) {
vector<int> G(n + 1, 0);
G[0] = 1, G[1] = 1;
// Iterating for different values of N, in Bottom Up Approach
for(int i = 0; i <= n; ++i) {
// Looking at each case with all nodes as roots
for(int j = 1; j <= i; ++j) {
// Number of total trees possible for current value of i:
// Possibilities for left subtree x Possibilities for right subtree
G[i] += G[j - 1] + G[i - j];
}
}
return G[n];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment