File tree 1 file changed +68
-0
lines changed
solution/0095.Unique Binary Search Trees II
1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @lc app=leetcode.cn id=95 lang=golang
3
+ * Accepted
4
+ * 9/9 cases passed (28 ms)
5
+ * Your runtime beats 94 % of golang submissions
6
+ * Your memory usage beats 100 % of golang submissions (8 MB)
7
+ */
8
+
9
+ /**
10
+ * Definition for a binary tree node.
11
+ * type TreeNode struct {
12
+ * Val int
13
+ * Left *TreeNode
14
+ * Right *TreeNode
15
+ * }
16
+ */
17
+
18
+ type Pair struct {
19
+ a , b interface {}
20
+ }
21
+
22
+ func generateTrees (n int ) []* TreeNode {
23
+ if n < 1 {
24
+ return []* TreeNode {}
25
+ }
26
+ cache := make (map [Pair ][]* TreeNode )
27
+ return createTrees (1 , n , cache )
28
+ }
29
+
30
+ func createTrees (start , end int , cache map [Pair ][]* TreeNode ) []* TreeNode {
31
+ var ret []* TreeNode
32
+ p := Pair {start , end }
33
+ if ret , ok := cache [p ]; ok {
34
+ return ret
35
+ }
36
+ if start > end {
37
+ ret = []* TreeNode {nil }
38
+ cache [p ] = ret
39
+ return ret
40
+ }
41
+ if start == end {
42
+ node := & TreeNode {
43
+ Val : start ,
44
+ Left : nil ,
45
+ Right : nil ,
46
+ }
47
+ ret = []* TreeNode {node }
48
+ cache [p ] = ret
49
+ return ret
50
+ }
51
+ ret = make ([]* TreeNode , 0 )
52
+ for i := start ; i <= end ; i ++ {
53
+ lefts := createTrees (start , i - 1 , cache )
54
+ rights := createTrees (i + 1 , end , cache )
55
+ for _ , left := range lefts {
56
+ for _ , right := range rights {
57
+ node := & TreeNode {
58
+ Val : i ,
59
+ Left : left ,
60
+ Right : right ,
61
+ }
62
+ ret = append (ret , node )
63
+ }
64
+ }
65
+ }
66
+ cache [p ] = ret
67
+ return ret
68
+ }
You can’t perform that action at this time.
0 commit comments