commit d5a8b6d70876bf6a425db8703344d97dafbd7b5e
parent 8a1900f1c2c4c261b35096e570a6035dcd966a49
Author: Dimitrije Dobrota <mail@dimitrijedobrota.com>
Date: Wed, 1 Feb 2023 00:35:52 +0100
Dynamic Programming I: Day 11
Diffstat:
3 files changed, 54 insertions(+), 0 deletions(-)
diff --git a/Problems/0096.cpp b/Problems/0096.cpp
@@ -0,0 +1,11 @@
+class Solution {
+public:
+ int numTrees(int n) {
+ vector<int> dp(n + 1);
+ dp[0] = dp[1] = 1;
+
+ for (int i = 2; i <= n; i++)
+ for (int j = 1; j <= i; j++) dp[i] += dp[j - 1] * dp[i - j];
+ return dp.back();
+ }
+};
diff --git a/Problems/0264.cpp b/Problems/0264.cpp
@@ -0,0 +1,41 @@
+// Brute force solution
+class Solution {
+public:
+ int nthUglyNumber(int n) {
+ priority_queue<long long, vector<long long>, greater<long long>> pq;
+ unordered_set<long long> us;
+ int count;
+
+ pq.push(1);
+ count = 1;
+ while (!pq.empty() && count < n) {
+ long long n = pq.top();
+ pq.pop();
+ for (int i : {2, 3, 5}) {
+ if (us.count(n * i)) continue;
+ pq.push(n * i);
+ us.insert(n * i);
+ }
+ count++;
+ }
+
+ return (int)pq.top();
+ }
+};
+
+// DP solution
+class Solution {
+public:
+ int nthUglyNumber(int n) {
+ vector<int> k(n);
+ k[0] = 1;
+ int t2 = 0, t3 = 0, t5 = 0;
+ for (int i = 1; i < n; i++) {
+ k[i] = min(k[t2] * 2, min(k[t3] * 3, k[t5] * 5));
+ t2 += k[i] == k[t2] * 2;
+ t3 += k[i] == k[t3] * 3;
+ t5 += k[i] == k[t5] * 5;
+ }
+ return k.back();
+ }
+};
diff --git a/README.md b/README.md
@@ -67,6 +67,7 @@ for solving problems.
| 0091 | Medium | [Decode Ways](Problems/0091.cpp) |
| 0093 | Medium | [Restore IP Addresses](Problems/0093.cpp) |
| 0094 | Easy | [Binary Tree Inorder Traversal](Problems/0094.cpp) |
+| 0096 | Medium | [Unique Binary Search Trees](Problems/0096.cpp) |
| 0098 | Medium | [Validate Binary Search Tree](Problems/0098.cpp) |
| 0099 | Medium | [Recover Binary Search Tree](Problems/0099.cpp) |
| 0100 | Easy | [Same Tree](Problems/0100.cpp) |
@@ -141,6 +142,7 @@ for solving problems.
| 0242 | Easy | [Valid Anagram](Problems/0242.cpp) |
| 0257 | Easy | [Binary Tree Paths](Problems/0257.cpp) |
| 0263 | Easy | [Ugly Number](Problems/0263.cpp) |
+| 0264 | Medium | [Ugly Number II](Problems/0264.cpp) |
| 0278 | Easy | [First Bad Version](Problems/0278.cpp) |
| 0279 | Medium | [Perfect Squares](Problems/0279.cpp) |
| 0283 | Easy | [Move Zeroes](Problems/0283.cpp) |