From caafed6c1ef8ac75c52456a44992f4fa243f11d7 Mon Sep 17 00:00:00 2001 From: Shahrear Bin Amin Date: Thu, 5 Jan 2023 18:50:16 +0600 Subject: [PATCH 1/2] added Unique Binary Search Tree with dynamic programming --- .../unique_binary_search_tree.dart | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 dynamic_programming/unique_binary_search_tree.dart diff --git a/dynamic_programming/unique_binary_search_tree.dart b/dynamic_programming/unique_binary_search_tree.dart new file mode 100644 index 0000000..784fa06 --- /dev/null +++ b/dynamic_programming/unique_binary_search_tree.dart @@ -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 { + int solve(int i, List dp) { + 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 dp = List.filled(20, -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); + }); +} From b71b6906d659df1849376f1f1b7591d3199f0bb0 Mon Sep 17 00:00:00 2001 From: Shahrear Bin Amin Date: Thu, 5 Jan 2023 20:08:33 +0600 Subject: [PATCH 2/2] removed hardcoded List dp length --- dynamic_programming/unique_binary_search_tree.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dynamic_programming/unique_binary_search_tree.dart b/dynamic_programming/unique_binary_search_tree.dart index 784fa06..ee5b3a9 100644 --- a/dynamic_programming/unique_binary_search_tree.dart +++ b/dynamic_programming/unique_binary_search_tree.dart @@ -17,7 +17,7 @@ class UniqueBST { } int numTrees(int n) { - List dp = List.filled(20, -1); + List dp = List.filled(n + 1, -1); return this.solve(n, dp); } }