. Unique Binary Search Treesgiven
NHow many structurally unique BST's (binary search trees) that store values 1 ...
N?
For example,
Given N = 3, there is a total of 5 unique BST ' s.
1 3 3 2 1 \// /\ 3 2 1 1 3 2 / / \ 2 1 2 3
Tree Dynamic Programming
Public classSolution { Public intNumtrees (intN) {//numtrees (n) = Sum (Numtrees (n-1-i) * Numtrees (n-1-i)), where I is [0,n-1] if(n==0) return1; int[] Nums =New int[N+1]; nums[0] = 1; NUMS[1] = 1; for(inti = 2; i<n+1; ++i) {intTotalchildren = i-1; for(intleft = 0; left<=totalchildren;++Left ) {Nums[i]+=nums[left]*nums[totalchildren-Left ]; } } returnNums[n]; /*public int numtrees (int n) {if (n==0) return 1; if (n <= 2) return n; int total = 0; for (int i = 1; i<=n;++i) {int left = Numtrees (i-1); int right = Numtrees (n-i); Total + = left * RIGHT; } return total; } */ }}
Unique Binary Search Trees II
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.
Given N = 3, your program should return all 5 unique BST ' s shown below.
1 3 3 2 1 \// /\ 3 2 1 1 3 2 / / \ 2 1 2 3
Tree Dynamic Programming
/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode RI Ght * TreeNode (int x) {val = x;} }*/ Public classSolution { PublicList<treenode> Generatetrees (intN) {returnGeneratetrees (1, N); } PrivateList<treenode> Generatetrees (intFromintTo ) {List<TreeNode> results =NewArraylist<treenode>(); if(From >to )returnresults; if(From = =To ) {Results.add (NewTreeNode (from)); returnresults; } for(inti = from; i<=to; ++i) {List<TreeNode> left = Generatetrees (from, i-1); List<TreeNode> right = Generatetrees (i+1, to); if(left.size () = = 0) { for(TreeNode r:right) {TreeNode root=NewTreeNode (i); Root.right=R; Results.add (root); } } Else if(right.size () = = 0) { for(TreeNode l:left) {TreeNode root=NewTreeNode (i); Root.left=l; Results.add (root); } } Else{ for(TreeNode l:left) { for(TreeNode r:right) {TreeNode root=NewTreeNode (i); Root.left=l; Root.right=R; Results.add (root); } } } } returnresults; }}
241. Different Ways to ADD parentheses
Given A string of numbers and operators, return all possible results from computing all the different possible ways to Gro Up numbers and operators. The valid operators + are, - and * .
Example 1
Input: "2-1-1" .
((2-1)-1) = 0 ((1-1)) = 2
Output:[0, 2]
Example 2
Input:"2*3-4*5"
((4*5)) =-34 ((2*3)-(4*5)) = 14 ((3-4)) = 10 (((3-4))) =-10 (((2*3) 4) = 10
Output:[-34, -14, -10, -10, 10]
Divide and Conquer
* Unique Binary Search Trees && 95. Unique Binary Search Trees II && 241. Different Ways to Add parentheses