Created
June 24, 2020 14:37
-
-
Save JyotinderSingh/bf5919b9c91630e863536d98b4a453de to your computer and use it in GitHub Desktop.
Unique Binary Search Trees (LeetCode) | Dynamic Programming
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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