diff --git a/Pattern10 - Subsets/Challenge3-Count_of_Structurally_Unique_Binary_Search_Trees/solution.go b/Pattern10 - Subsets/Challenge3-Count_of_Structurally_Unique_Binary_Search_Trees/solution.go new file mode 100644 index 0000000..b3104da --- /dev/null +++ b/Pattern10 - Subsets/Challenge3-Count_of_Structurally_Unique_Binary_Search_Trees/solution.go @@ -0,0 +1,41 @@ +package Challenge3_Count_of_Structurally_Unique_Binary_Search_Trees + +/* +已经在challenge2中实现 +ref: https://leetcode-cn.com/problems/unique-binary-search-trees/ +*/ +func numTrees(n int) int { + var bfs func(int, int) int + var m = make(map[Range]int) + bfs = func(start, end int) int { + var res = 0 + if start == end { + return 1 + } + if v, ok := m[Range{start, end}]; ok { + return v + } + for i := start; i <= end; i++ { + if i == start { + res += bfs(i+1, end) + continue + } + if i == end { + res += bfs(start, i-1) + continue + } + left := bfs(start, i-1) + right := bfs(i+1, end) + res += left * right + } + m[Range{start, end}] = res + return res + } + + return bfs(1, n) +} + +type Range struct { + start int + end int +} diff --git a/Pattern10 - Subsets/Challenge3-Count_of_Structurally_Unique_Binary_Search_Trees/solution_test.go b/Pattern10 - Subsets/Challenge3-Count_of_Structurally_Unique_Binary_Search_Trees/solution_test.go new file mode 100644 index 0000000..1be7a6e --- /dev/null +++ b/Pattern10 - Subsets/Challenge3-Count_of_Structurally_Unique_Binary_Search_Trees/solution_test.go @@ -0,0 +1,26 @@ +package Challenge3_Count_of_Structurally_Unique_Binary_Search_Trees + +import "testing" + +func Test_NumTrees(t *testing.T){ + type args struct { + n int + } + tests := []struct { + name string + args args + want int + }{ + {"case1", args{2}, 2}, + {"case2", args{3}, 5}, + {"case3", args{1}, 1}, + {"case4", args{4}, 14}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := numTrees(tt.args.n); got != tt.want { + t.Errorf("numTrees() = %v, want %v", got, tt.want) + } + }) + } +} \ No newline at end of file