Skip to content

Commit 87034c4

Browse files
committed
Implement unique-binary-search-trees
name: unique-binary-search-trees url: https://leetcode.com/problems/unique-binary-search-trees difficulty: 2 time: 100.0 ms time-rank: -1 % time-complexity: O(N) space: 5.9 MB space-rank: 92.28 % space-complexity: O(N) Fixes #155 Signed-off-by: Christopher Friedt <[email protected]>
1 parent 92bcff4 commit 87034c4

2 files changed

+78
-0
lines changed

unique-binary-search-trees-test.cpp

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/*
2+
* Copyright (c) 2021, Christopher Friedt
3+
*
4+
* SPDX-License-Identifier: MIT
5+
*/
6+
7+
#include <gtest/gtest.h>
8+
9+
#include "unique-binary-search-trees.cpp"
10+
11+
using namespace std;
12+
13+
TEST(UniqueBinarySearchTrees, 1) {
14+
EXPECT_EQ(1, Solution().numTrees(1));
15+
}
16+
17+
TEST(UniqueBinarySearchTrees, 2) {
18+
EXPECT_EQ(2, Solution().numTrees(2));
19+
}
20+
21+
TEST(UniqueBinarySearchTrees, 3) {
22+
EXPECT_EQ(5, Solution().numTrees(3));
23+
}
24+
25+
TEST(UniqueBinarySearchTrees, 4) {
26+
EXPECT_EQ(5, Solution().numTrees(3));
27+
}

unique-binary-search-trees.cpp

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/*
2+
* Copyright (c) 2021, Christopher Friedt
3+
*
4+
* SPDX-License-Identifier: MIT
5+
*/
6+
7+
// clang-format off
8+
// name: unique-binary-search-trees
9+
// url: https://leetcode.com/problems/unique-binary-search-trees
10+
// difficulty: 2
11+
// clang-format on
12+
13+
#include <vector>
14+
15+
using namespace std;
16+
17+
class Solution {
18+
public:
19+
int helper(vector<int>& dp, int n) {
20+
if (dp[n] != 0) {
21+
return dp[n];
22+
}
23+
24+
int m = 0;
25+
for(int root = 1; root <= n; ++root) {
26+
int before = root - 1;
27+
int after = n - root;
28+
29+
m += helper(dp, before) * helper(dp, after);
30+
}
31+
32+
dp[n] = m;
33+
return m;
34+
}
35+
36+
int numTrees(int n) {
37+
// the solution is structurally recursive
38+
// n | root | numTrees(n)
39+
// ---------------
40+
// 0 | | 1
41+
// 1 | | 1
42+
// 2 | 1 | 1
43+
// | 2 | +1 = 2
44+
// 3 | 1 | numTress(0) * numTrees(2)
45+
// | 2 | + numTrees(1) * numTrees(1)
46+
// | 3 | + numTrees(2) * numTrees(0) = 5
47+
vector<int> dp(n + 1, 0);
48+
dp[0] = 1;
49+
return helper(dp, n);
50+
}
51+
};

0 commit comments

Comments
 (0)