标签:
For example,
Given n = 3, there are a total of 5 unique BST‘s.
1 3 3 2 1 \ / / / \ 3 2 1 1 3 2 / / \ 2 1 2 3
public class Solution { public int numTrees(int n) { //numTrees(n) = Sum(numTrees(n-1-i) * numTrees(n-1-i)), where i is [0,n-1] if(n==0) return 1; int[] nums = new int[n+1]; nums[0] = 1; nums[1] = 1; for(int i = 2; i<n+1; ++i) { int totalChildren = i - 1; for(int left = 0; left<=totalChildren;++left) { nums[i]+=nums[left]*nums[totalChildren-left]; } } return nums[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; } */ } }
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
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<TreeNode> generateTrees(int n) { return generateTrees(1,n); } private List<TreeNode> generateTrees(int from, int to) { List<TreeNode> results = new ArrayList<TreeNode>(); if(from > to) return results; if(from == to){ results.add(new TreeNode(from)); return results; } for(int i = 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 = new TreeNode(i); root.right = r; results.add(root); } } else if(right.size() == 0) { for(TreeNode l:left){ TreeNode root = new TreeNode(i); root.left = l; results.add(root); } } else{ for(TreeNode l:left){ for(TreeNode r:right){ TreeNode root = new TreeNode(i); root.left = l; root.right = r; results.add(root); } } } } return results; } }
Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +
, -
and *
.
Input: "2-1-1"
.
((2-1)-1) = 0 (2-(1-1)) = 2
Output: [0, 2]
Input: "2*3-4*5"
(2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10
Output: [-34, -14, -10, -10, 10]
标签:
原文地址:http://www.cnblogs.com/neweracoding/p/5722323.html