Skip to content

Commit

Permalink
add: solution for Challenge3_Count_of_Structurally_Unique_Binary_Sear…
Browse files Browse the repository at this point in the history
…ch_Trees
  • Loading branch information
zhiwei-Feng committed May 8, 2021
1 parent 1715eab commit f490571
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -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
}
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}

0 comments on commit f490571

Please sign in to comment.