From f9e9a910b7acce4c4bec3e8b098ae9b239356ea7 Mon Sep 17 00:00:00 2001 From: Gleb Koval Date: Mon, 8 Nov 2021 12:56:51 +0000 Subject: [PATCH] unique-binary-search-trees --- unique-binary-search-trees/sol.go | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 unique-binary-search-trees/sol.go diff --git a/unique-binary-search-trees/sol.go b/unique-binary-search-trees/sol.go new file mode 100644 index 0000000..64d28cc --- /dev/null +++ b/unique-binary-search-trees/sol.go @@ -0,0 +1,26 @@ +package main + +// Time: O(n^2) +// Space: O(n) +func numTrees(n int) int { + if n < 3 { + return n + } + trees := map[int]int{ + 0: 1, + 1: 1, + 2: 2, + } + for c := 3; c <= n; c++ { + s := 0 + for p := 0; p < c/2; p++ { + s += trees[p] * trees[c-p-1] * 2 + } + if (c-1)%2 == 0 { + p := (c - 1) / 2 + s += trees[p] * trees[p] + } + trees[c] = s + } + return trees[n] +}