Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added Unique Binary Search Tree with dynamic programming #210

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions dynamic_programming/unique_binary_search_tree.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import 'package:test/test.dart';

// Problem - https://leetcode.com/problems/unique-binary-search-trees/description/
// Given an integer n, return the number of structurally unique BST's (binary search trees)
// which has exactly n nodes of unique values from 1 to n.

class UniqueBST {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this class is not serving any purpose. we can remove it.

int solve(int i, List<int> dp) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you add some comments to explain the algorithm

if (i == 0 || i == 1) return 1;
if (dp[i] != -1) return dp[i];

int total = 0;
for (int k = 1; k <= i; k++) {
total += solve(k - 1, dp) * solve(i - k, dp);
}
return dp[i] = total;
}

int numTrees(int n) {
List<int> dp = List.filled(n + 1, -1);
return this.solve(n, dp);
}
}

void main() {
var uniqueBST = UniqueBST();
test('Test Case 1: Input 3, Output - 5', () {
expect(uniqueBST.numTrees(3), 5);
});

test('Test Case 2: Input 1, Output - 1', () {
expect(uniqueBST.numTrees(1), 1);
Comment on lines +27 to +32
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could you please add more test cases ?

});
}