unique-binary-search-trees.dart (1085B)
1 //Given a number n assume that you have n 2 //numbers from 1 to n return the total number 3 //of unique trees that can be created from the list. 4 5 //To solve this you need to make every node in the current 6 //list the root. Then from there recurse the left and right sides 7 //based on the values greater than and less than the given node. 8 //From here multiply the left and right options together because 9 //for each version permutation of the left subtree if you change one on 10 //the right then there is an entire new set of permutations for the tree. 11 12 13 class Solution { 14 int numTrees(int n) { 15 List<int> val_list = []; 16 for(int i = 1 ; i <= n ; ++i){ 17 val_list.add(i); 18 } 19 return trees(val_list); 20 } 21 22 int trees(List<int> vals){ 23 if(vals.length == 1){ 24 return 1; 25 } 26 27 int current_val = 0; 28 for(int i = 0 ; i < vals.length ; ++i){ 29 List<int> left = vals.sublist(0,i); 30 List<int> right = vals.sublist(i + 1); 31 current_val += trees(left); 32 current_val += trees(right); 33 } 34 return current_val; 35 } 36 }