标签:ons div style tco time class put sea span
Given an integer n, return the number of structurally unique BST‘s (binary search trees) which has exactly n nodes of unique values from 1 to n. Example 1: Input: n = 3 Output: 5 Example 2: Input: n = 1 Output: 1 Constraints: 1 <= n <= 19
Recursion, Time-out
class Solution { public int numTrees(int n) { int res = 0; for (int i = 1; i <= n; i++) { res = res + helper(i, n, 1); } return res; } public int helper(int current, int h, int l) { if (h == l && current == l) { return 1; } int left = 0; for (int i = l; i< current; i++) { left = left+ helper(i, current-1, l); } int right = 0; for (int i = h; i > current; i--) { right = right + helper(i, h, current+1); } if (left == 0) { return right; } if (right == 0) { return left; } return left * right; } }
LeetCode - Unique Binary Search Trees
标签:ons div style tco time class put sea span
原文地址:https://www.cnblogs.com/incrediblechangshuo/p/14416563.html