-
Notifications
You must be signed in to change notification settings - Fork 21
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add: solution for Challenge3_Count_of_Structurally_Unique_Binary_Sear…
…ch_Trees
- Loading branch information
1 parent
1715eab
commit f490571
Showing
2 changed files
with
67 additions
and
0 deletions.
There are no files selected for viewing
41 changes: 41 additions & 0 deletions
41
Pattern10 - Subsets/Challenge3-Count_of_Structurally_Unique_Binary_Search_Trees/solution.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
26 changes: 26 additions & 0 deletions
26
...10 - Subsets/Challenge3-Count_of_Structurally_Unique_Binary_Search_Trees/solution_test.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
}) | ||
} | ||
} |